1

In the main array, I have:

 $array=array('index1'=>'value1', 'index2'=>'value2' , ....);

In another array, I keep the key=>index relationship:

$map=array('key1'=>'index1', 'key2'=>'index2' , ...);

Is there any simple way to combile these two array into one to get:

$combine=array('key1'=>'value1', 'key2'=>'value2', ...);

that is values from main array and keys comes from the map array.

1
  • 1
    Have you tried something or did some research ? Commented May 29, 2015 at 9:38

4 Answers 4

2
<?php 

$array1=array('index1'=>'value1', 'index2'=>'value2');
$array2=array('key1'=>'index1', 'key2'=>'index2');

foreach($array2 as $key => $val){
    if(array_key_exists($val,$array1))
        $combined[$key] = $array1[$val];
}

// Output
print_r($combined);


?>

Output

Array
(
    [key1] => value1
    [key2] => value2
)
Sign up to request clarification or add additional context in comments.

Comments

1

Loop through the $map array and extract the value for $array accordingly and put them to the $combine array. You can try this -

$array=array('index1'=>'value1', 'index2'=>'value2');
$map=array('key1'=>'index1', 'key2'=>'index2');

$combine = array();

foreach($map as $key => $val) {
    $combine[$key] = $array[$val];
}
var_dump($combine);

Output

array(2) {
  ["key1"]=>
  string(6) "value1"
  ["key2"]=>
  string(6) "value2"
}

Comments

1

A possible solution here, if the keys and values already are in the expected order, and you are certain all arrays have the same length, use the array_combine function together with array_keys and array_values

<?php
$array=array('index1'=>'value1', 'index2'=>'value2');
$map=array('key1'=>'index1', 'key2'=>'index2');

$combine = array_combine( array_keys($map), array_values($array) );

print_r($combine);
?>

Output

Array
(
    [key1] => value1
    [key2] => value2
)

2 Comments

Huff, good thing all keys are in the correct order, otherwise your entire code would break..
@Rizier123 > Yes, you are correct. The keys and values need to be in the correct order, as I stated in the answer - and also they need to be the same length, although PHP will return FALSE if they are not.
1

Variant with no own code, only functions. It takes only keys presented in both arrays:

$array=array('index1'=>'value1', 'index2'=>'value2' , 'index3'=>'value3');
$map=array('key1'=>'index1', 'key2'=>'index2');

// next two lines if arrays may be of different length
$newmap = array_intersect_key(array_flip($map), $array);
$newarray = array_intersect_key($array, $newmap);

$new = array_combine($newmap, $newarray);
var_dump ($new);

output:

array(2) { ["key1"]=> string(6) "value1" ["key2"]=> string(6) "value2" }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.