Find the count of array with specific key and value in php

后端 未结 2 1587
难免孤独
难免孤独 2021-01-25 07:09

I have a multidimensional array with following values

$array = array( 
            0 => array (
               \"id\" => 1,
               \"parent_id\" =&         


        
2条回答
  •  野性不改
    2021-01-25 07:21

    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.

提交回复
热议问题