Pieter Dijkstra
Pieter Dijkstra

Reputation: 121

How to filter an array by keys using another array

I working now for a couple of hours on my project, i have some key's from a early array that i want to loop to my new array and pick the value of the key's that i have from the early array.

Early array:

$old_keys = ['key1','key2','key3'];

New array:

$result = ['key1' => 'foo', 'key2' => 'bar', 'key6' => 'ipsum'];

Output that i want is:

$output = ['foo', 'bar'];

This is what i made:

foreach ($old_keys as $old_key) {

    $output[] = array_column($result, $old_key);

}
return $output;

What did i wrong because everything what i get is a empty array

Thanks a lot!

Update:

$keys = array_flip($old_keys);

$output = array_values(array_intersect_key($result, $keys));

echo '<pre>';
var_dump($output);

The $output is now filled with the multidimensional array of $result, but the values 'foo' and 'bar' are in the second level of this multidimensional array. The problem is, i get only the first level of this array and not the second level.

example of the output:

[
 [0] => string
 [1] => string
 [
  [key1] => foo
  [key2] => bar
 ]
]

What i want is:

[
 [0] => string
 [1] => string
 [3] => foo
 [4] => bar
]

Solution:

$flat = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($result)), true);

Upvotes: 1

Views: 265

Answers (1)

mickmackusa
mickmackusa

Reputation: 47894

Filter the $result array using $old_keys, but use the $old_keys values as keys:

$old_keys = array_flip(['key1','key2','key3']);
$result = ['key1' => 'foo', 'key2' => 'bar', 'key6' => 'ipsum'];
$output=array_intersect_key($result,$old_keys);
print_r($output);

If you want to re-index the keys in the result, replace the $output declaration with:

$output=array_values(array_intersect_key($result,$old_keys));

Upvotes: 1

Related Questions