How to search by key=>value in a multidimensional array in PHP

前端 未结 15 2085
闹比i
闹比i 2020-11-22 00:13

Is there any fast way to get all subarrays where a key value pair was found in a multidimensional array? I can\'t say how deep the array will be.

Simple example arra

15条回答
  •  星月不相逢
    2020-11-22 00:51

    How about the SPL version instead? It'll save you some typing:

    // I changed your input example to make it harder and
    // to show it works at lower depths:
    
    $arr = array(0 => array('id'=>1,'name'=>"cat 1"),
                 1 => array(array('id'=>3,'name'=>"cat 1")),
                 2 => array('id'=>2,'name'=>"cat 2")
    );
    
    //here's the code:
    
        $arrIt = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
    
     foreach ($arrIt as $sub) {
        $subArray = $arrIt->getSubIterator();
        if ($subArray['name'] === 'cat 1') {
            $outputArray[] = iterator_to_array($subArray);
        }
    }
    

    What's great is that basically the same code will iterate through a directory for you, by using a RecursiveDirectoryIterator instead of a RecursiveArrayIterator. SPL is the roxor.

    The only bummer about SPL is that it's badly documented on the web. But several PHP books go into some useful detail, particularly Pro PHP; and you can probably google for more info, too.

提交回复
热议问题