0

What is the easiest way to search in such an array? E.g. search for 5f8ff7a0c49db9d and return 5f8ff7bee02fd05

This doesn't work:

array_search('5f8ff7a0c49db9d', array_column($arr, 1))


[0] : Array
(
    [0] => Array
        (
            [5f8ff7bedde211e] => 5f8e6a74c1d4efe
        )

    [1] => Array
        (
            [5f8ff7bee02fd05] => 5f8ff7a0c49db9d
        )

    [2] => Array
        (
            [5f8ff7bee2735ce] => 5f8ff7a0c6e8039
        )

)
smolo
  • 737
  • 1
  • 15
  • 27

2 Answers2

1

You can reduce the whole array as following:

$keyedByValue = array_reduce($arr, static function(array $carry, array $item) {
    return array_merge($carry, array_reverse($item));
}, []);

$yourKey = $keyedByValue['5f8ff7a0c49db9d'];

Or you can even use a simple loop:

$result = null;
$search = '5f8ff7a0c49db9d';

foreach ($arr as $item) {
    $item = array_reverse($item);

    if (isset($item[$search])) {
         $result = $item[$search];
         break;
    }
}
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50
0

array_search has this in the examples:

$foundKey = array_search($needle, array_column($array, 'key')); 

which works fine

Ron
  • 5,900
  • 2
  • 20
  • 30
  • My keys don't have names (no 'key'). How do I use array_column() in my case? – smolo Oct 21 '20 at 12:41
  • Did you see this: https://stackoverflow.com/questions/6661530/php-multidimensional-array-search-by-value – Ron Oct 21 '20 at 12:45