开发者

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 hav开发者_StackOverflow中文版e:

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)

e.g:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜