PHP, combine two arrays into a new array using the first values ​​of the array as keys

I have two arrays that I want to combine. I need to take values ​​from the first array, use these values ​​as keys for matching with the second array and combine them into a third array (the one that I will use).

In other words, I have this first array:

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

My second array:

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
)

It seems easy enough, but I can't figure it out. I tried various array functions, such as array_intersect_key, with no luck.

+3
source share
4 answers

Here's a simple imperative solution :

$combined = array();

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

And functional solution:

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

:

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

:

$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);

:

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

array_keys ,

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
-1
source

Source: https://habr.com/ru/post/1785305/


All Articles