Skip to content

Instantly share code, notes, and snippets.

@ostrolucky
Created June 6, 2019 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ostrolucky/d0c6490ca5503b35c5b5c8226c6db6bb to your computer and use it in GitHub Desktop.
Save ostrolucky/d0c6490ca5503b35c5b5c8226c6db6bb to your computer and use it in GitHub Desktop.
array_select
<?php
function array_select(array $array, array $filter): array
{
return array_map(function (array $object) use ($filter) {
$object = array_intersect_key($object, $filter);
foreach ($object as $key => $value) {
if (is_array($filter[$key])) {
$object[$key] = array_select($object[$key], $filter[$key]);
}
}
return $object;
}, $array);
}
$array = json_decode('[
{
"_id": "5cf685bd902ff4cb44382c9c",
"index": 0,
"friends": [
{
"id": 0,
"name": "Sandoval Salas"
},
{
"id": 1,
"name": "Potter Gross"
}
]
}
]', true);
$result = array_select($array, [
'index' => true,
'friends' => ['id' => true],
]);
print_r($result);
/*
Output for 7.1.25 - 7.3.6
Array
(
[0] => Array
(
[index] => 0
[friends] => Array
(
[0] => Array
(
[id] => 0
)
[1] => Array
(
[id] => 1
)
)
)
)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment