Ormoz
Ormoz

Reputation: 3013

Change Array Keys with a Map Array in PHP

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.

Upvotes: 1

Views: 196

Answers (4)

splash58
splash58

Reputation: 26153

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" }

Upvotes: 1

Jacob Overgaard
Jacob Overgaard

Reputation: 51

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
)

Upvotes: 1

Akshay Hegde
Akshay Hegde

Reputation: 16997

<?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
)

Upvotes: 2

Sougata Bose
Sougata Bose

Reputation: 31749

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"
}

Upvotes: 1

Related Questions