Created
June 6, 2019 09:31
-
-
Save ostrolucky/d0c6490ca5503b35c5b5c8226c6db6bb to your computer and use it in GitHub Desktop.
array_select
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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