简体   繁体   中英

PHP, combine two arrays into a new array, using the first array's values as the keys

I have two arrays I want to combine. I need to take the values from the first array, use these values as the keys to match from the second array, and combine them into a third array (the one I'll use).

In other words, I have this first array:

Array
(
[24] => 5
[26] => 4
[27] => 2
)

The second array I have:

Array
(
[1] => McDonalds
[2] => Burger King
[3] => Wendys
[4] => Taco Bell
[5] => Hardees
)

And finally, this is the array I want to have:

Array
(
[5] => Hardees
[4] => Taco Bell
[2] => Burger King
)

Seems easy enough, but I can't seem to figure it out. I've tried various array functions, such as array_intersect_key, with no luck.

Here's a simple imperative solution:

$combined = array();

foreach ($array1 as $v) {
    if (isset($array2[$v])) {
        $combined[$v] = $array2[$v];
    }
}

And a functional solution:

// Note that elements of $combined will retain the order of $array2, not $array1
$combined = array_intersect_key($array2, array_flip($array1));
$result = array();
foreach (array_flip($keys) as $k) {
    $result[$k] = $values[$k];
}

In just one line:

foreach ($a as $v) $c[$v]=$b[$v];

See:

$a=array(24=>5,26=>4,27=>2);
$b=array(1=>'McDonalds',2=>'Burger King',3=>'Wendys',4=>'Taco Bell',5=>'Hardees');

foreach ($a as $v) $c[$v]=$b[$v];

print_r($c);

It returns:

Array
(
    [5] => Hardees
    [4] => Taco Bell
    [2] => Burger King
)

array_keys does what you want natively

The first argument is the array of your fast food restaurants, the second argument is the first array you gave (the keys you want)

eg:

$array = array_keys(array(0 => 'McDonalds', 1 => 'BurgerKing', 2 => 'Taco Bell'),
  array(0 => 1));
$array will only have BurgerKing in it

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