0

I have two arrays. The first $letters is simple:

[5, 89, 1, 212]

The second $some_data:

[
 89 => 'A',
 41 => 'B',
 1  => 'C',
 5  => 'D',
 200 => 'E',
 212 => 'F'
]

How to merge those arrays to get:

[
89 => 'A',
1  => 'C',
5  => 'D',
212 => 'F'
]

I have already tried

foreach($some_data as $id => $title) {
        if (array_key_exists($id, $letters)) {
            $some_arr[$id] = $title;
        }
    }

But for some reason it's not working properly and $some_arr is duplicated. This function, that fills up $some_arr is called inside a loop and accepts one parameter. Using this parameter, I fill up array $letters. Each time (in general 6 times) array $letter is different

$some_arr wasn't duplicated, when it used to fill up this way:

foreach($cont_cntrs as $cntr_id) {
        $cntrs_byletter[$cntr_id] = $countries[$cntr_id];
    }

But it wasn't sorted by $countries id's order

Bipa
  • 233
  • 1
  • 2
  • 10

3 Answers3

2

You just want to keep all the entries which exist in the $letters array. So use an array intersection:

$some_arr = array_intersect_key($some_data, array_flip($letters));
deceze
  • 491,798
  • 79
  • 706
  • 853
0

you can use 'in_array' function instead on array_key_exits,

As you are comparing values with another array.

$some_arr = [];
foreach($some_data as $id => $title) {
  if (in_array($id, $letters)) {
      $some_arr[$id] = $title;
    }
}
Gajanan Kolpuke
  • 167
  • 1
  • 1
  • 13
0

Do loop on $letters array and then use array_key_exists function to check key value pairs exist. If exists then assign key value pair in new array as:

    $some_arr = [];
    foreach($letters as $value) {
            if (array_key_exists($value, $some_data)) {
                $some_arr[$value] = $some_data[$value];
            }
        }
asort($some_arr);//sort associative arrays in ascending order, according to the value

Expected output:

    Array
(
    [89] => A
    [1] => C
    [5] => D
    [212] => F
)
Gufran Hasan
  • 8,059
  • 7
  • 33
  • 48