在PHP中找到具有特定键和值的数组的计数 [英] Find the count of array with specific key and value in php

查看:52
本文介绍了在PHP中找到具有特定键和值的数组的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下值的多维数组

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
            )
         );

我想查找特定ID的孩子人数. 就我而言,我希望结果像

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

我知道这是通过使用 for循环完成的.该函数是否存在任何PHP数组函数?

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

推荐答案

您可以将count与 array_filter

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);
}

或更短的版本

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

因此基本上,它会获取$ id等于parent_id的元素并返回其计数

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

这篇关于在PHP中找到具有特定键和值的数组的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆