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

后端 未结 2 1559
难免孤独
难免孤独 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.

    0 讨论(0)
  • 2021-01-25 07:30

    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

    0 讨论(0)
提交回复
热议问题