简体   繁体   中英

Replace one array keys with second array values

I need to combine two arrays, the key from the first array should be replaced with the respective value from the second array. The following code works fine if both arrays have the same number of elements and if they have the same order.

$first = array("a"=>"red", "b"=>"green", "c"=>"blue");

$second = array("a"=>"sun", "b"=>"grass", "c"=>"sky");

$new = array_combine($second, $first);

print_r($new);

Result

Array
(
    [sun] => red
    [grass] => green
    [sky] => blue
)

But I need this to work in a scenario where they don´t have the same elements number or not in the same order. How can I achieve it?

If you need to trim your arrays so that you can use array_combine() the approach below will make both the same length by trimming the biggest one and then will combine them.

$first = array("a"=>"red", "b"=>"green", "c"=>"blue");

$second = array("a"=>"sun", "b"=>"grass", "c"=>"sky", "d" => "moon");

$first = array_slice($first, 0, count($second));
$second = array_slice($second, 0, count($first));

$new = array_combine($second, $first);

print_r($new);

Results in:

Array
(
    [sun] => red
    [grass] => green
    [sky] => blue
)

It works in all cases:

  • $first bigger than $second .
  • $second bigger than $first .
  • $first and $second has the same size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM