Find the count of array with specific key and valu

2020-04-21 01:36发布

问题:

I have a multidimensional array with following values

$array = array( 
            0 => array (
               "id" => 1,
               "parent_id" => 0
            ),            
            1 => array (
               "id" => 2,
               "parent_id" => 1
            ),            
            2 => array (
               "id" => 3,
               "parent_id" => 1,
            )
            3 => array (
               "id" => 4,
               "parent_id" => 0
            )
            4 => array (
               "id" => 5,
               "parent_id" => 3
            )
         );

I want to find the count of children for particular id. In my case, I want the results to be like

find_children($array, 1);
// output : 2

find_children($array, 3);
// output : 1

I know this is done by using for loop. Is there any PHP array functions exist for this function?

回答1:

You can use count with array_filter

function doSearch($id, array $array) {

    $arr = array_filter($array, function ($var) use ($id){
        if ($id === $var['parent_id']) {
           return true;
        }
    });

    return count($arr);
}

or shorter version

function doSearch($id, array $array) {
    return count(array_filter($array, function($var) use ($id) {
        return $id === $var['parent_id'];
    }));
}

So basically it gets elements where $id is equal to parent_id and returns their count



回答2:

You could implement it using array_filter, to filter the array down to the elements that match a given parent id, and then return the count of the filtered array. The filter is provided a callback, which is run over each element of the given array.

function find_children($array, $parent) {
  return count(array_filter($array, function ($e) use ($parent) {
    return $e['parent_id'] === $parent;
  }));
}

find_children($array, 1);  // 2
find_children($array, 3);  // 1
find_children($array, 10); // 0

Whether or not you prefer this to a loop is a matter of taste.



标签: php arrays