php - How can I find values in an array which match criteria, without using a for loop? -


i have array this

$a = [     [         "id"     => "1",         "values"   => [             "1",             "2"         ]     ],     [         "id"     => "2",         "values"   => [             "1",             "3"         ]     ],     [         "id"     => "3",         "values"   => [             "2",             "4"         ]     ],     [         "id"     => "4",         "values"   => [             "4",             "6"         ]     ], ]; 

to search , return array 'values' has 2

$result = [     [         "id"     => "1",         "values"   => [             "1",             "2"         ]     ],     [         "id"     => "3",         "values"   => [             "2",             "4"         ]     ], ]; 

yes, can loop, , use in_array return result, thinking whether there elegant (better) way it?

$result = []; foreach ($a $datum) {     if (in_array('2', $datum['values'])) {         $result[] = $datum;     } } 

i tried array_search, not support nested array

array_search('2', array_column($a, 'values'));

you can use array_filter() , in_array():

$value = '2';  $result = array_filter($a, function (array $element) use ($value) {     return array_key_exists('values', $element)          && is_array($element['values'])          && in_array($value, $element['values'], true); });  var_dump($result); 

for reference, see:

for example, see:


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -