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

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

提交回复
热议问题