using array_search for multi dimensional array

后端 未结 6 669
误落风尘
误落风尘 2020-11-29 06:37

using array_search in a 1 dimensional array is simple

$array = array(\"apple\", \"banana\", \"cherry\");
$searchValue = \"cherry\";
$key = array_search($sear         


        
6条回答
  •  情深已故
    2020-11-29 06:58

    Hooray for one-liners!

    $index = array_keys(array_filter($array, function($item){ return $item['property'] === 'whatever';}))[0];
    

    Let's make it more clear:

    array_filter(
        $array, 
        function ($item) {
            return $item['property'] === 'whatever';
        }
    ); 
    

    returns an array that contains all the elements that fulfill the condition in the callback, while maintaining their original array keys. We basically need the key of the first element of that array.

    To do this we wrap the result in an array_keys() call and get it's first element. This specific example makes the assumption that at least one matching element exists, so you might need an extra check just to be safe.

提交回复
热议问题