获取PHP中值相似的数组的计数

时间:2017-09-14 08:58:01

标签: php arrays

我有一个数组:

[
class: [
        0: "538c5cd9dda3aae409000038",
        1: "538c5cd9dda3aae409000037"
        ],
section: [
          0: "O",
          1: "N"
          ],
religion: "",
gender: "",
nationality: "",
bloodgroup: "",
quota: "",
shorting: "rollno",
fieldstudentname: "on",
fieldrollno: "on",
fieldreligion: "on",
fieldaddress: "on",
fieldgender: "on",
fieldaadhar: "on",
fieldcategory: "on",
classbulklist: "Search"
] 

现在,我只希望计数值为“on”。在上面的例子中,计数将是7.如何在不使用foreach循环的情况下实现此目的。

2 个答案:

答案 0 :(得分:1)

您可以使用array_filter()过滤掉不匹配的值,然后计算结果。

$callback = function($value) {
    return ($value === "on");
};

$count = count(array_filter($your_array, $callback));

类似的回调也可以用作array_walk()的计数器回调(尽管array_filter()也可以),但这与使用常规循环完全不同。

答案 1 :(得分:0)

当您使用非PHP语法指定数组时(但更像JavaScript语法),我将假设您的数组是这样的:

$data = [
    (object) [
        "class" => (object) [
            0 => "538c5cd9dda3aae409000038",
            1 => "538c5cd9dda3aae409000037"
        ],
        "section" => (object) [
            0 => "O",
            1 => "N"
        ],
        "religion" => "",
        "gender" => "",
        "nationality" => "",
        "bloodgroup" => "",
        "quota" => "",
        "shorting" => "rollno",
        "fieldstudentname" => "on",
        "fieldrollno" => "on",
        "fieldreligion" => "on",
        "fieldaddress" => "on",
        "fieldgender" => "on",
        "fieldaadhar" => "on",
        "fieldcategory" => "on",
        "classbulklist" => "Search"
    ]
];

在这种情况下,您需要首先获取数组的第一个元素(它只有一个元素),然后将该对象作为具有get_object_vars的关联数组,然后对其值应用过滤器,最后得到结果数组的计数:

$count = count(array_filter(get_object_vars($data[0]), function ($val) {
    return $val === "on";
}));

编辑后

......似乎你没有对象,只有嵌套数组。在这种情况下,您应该省略对get_object_vars的调用:

$count = count(array_filter($data[0], function ($val) {
    return $val === "on";
}));