计算数组中的非空值(php)

时间:2017-06-17 22:09:16

标签: php arrays multidimensional-array filter array-filter

我已经尝试了搜索,但我的问题在那里没有解决,因为我的情况似乎有点不同。

这是我的阵列:

array(14) { [0]=> array(4) { ["index"]=> int(1) ["name"]=> string(19) "Parge Lenis die ..." ["score"]=> int(0) ["time"]=> string(8) "05:51:23" } [1]=> array(4) { ["index"]=> int(2) ["name"]=> string(8) "jiengels" ["score"]=> int(0) ["time"]=> string(8) "05:51:18" } [2]=> array(4) { ["index"]=> int(3) ["name"]=> string(6) "n!n-oX" ["score"]=> int(0) ["time"]=> string(8) "05:47:27" } [3]=> array(4) { ["index"]=> int(4) ["name"]=> string(8) "Maraskan" ["score"]=> int(0) ["time"]=> string(8) "05:44:45" } [4]=> array(4) { ["index"]=> int(5) ["name"]=> string(0) "" ["score"]=> int(0) ["time"]=> string(8) "05:42:56" } [5]=> array(4) { ["index"]=> int(6) ["name"]=> string(0) "" ["score"]=> int(0) ["time"]=> string(8) "04:32:21" } [6]=> array(4) { ["index"]=> int(7) ["name"]=> string(5) "Heavy" ["score"]=> int(0) ["time"]=> string(8) "03:29:39" } [7]=> array(4) { ["index"]=> int(8) ["name"]=> string(0) "" ["score"]=> int(0) ["time"]=> string(8) "02:59:28" } [8]=> array(4) { ["index"]=> int(9) ["name"]=> string(0) "" ["score"]=> int(0) ["time"]=> string(8) "02:54:37" } [9]=> array(4) { ["index"]=> int(10) ["name"]=> string(0) "" ["score"]=> int(0) ["time"]=> string(8) "02:53:33" } [10]=> array(4) { ["index"]=> int(11) ["name"]=> string(6) "Fischi" ["score"]=> int(0) ["time"]=> string(8) "02:12:36" } [11]=> array(4) { ["index"]=> int(12) ["name"]=> string(0) "" ["score"]=> int(0) ["time"]=> string(8) "02:02:50" } [12]=> array(4) { ["index"]=> int(13) ["name"]=> string(0) "" ["score"]=> int(0) ["time"]=> string(8) "01:09:53" } ["count"]=> int(13) }

有些条目对“名称”没有任何价值 - 因此我只想计算那些有名字的条目。

但是“array_filter”至少没有帮助我尝试使用它:( => array_filter($ myarray);

2 个答案:

答案 0 :(得分:3)

您可以在名称colume上使用array_filter,如live demo

echo count(array_filter(array_column($array, 'name')));

答案 1 :(得分:0)

您可以使用下面的array_filter()

<?php

$array = array(
            array("index" => 1, "name" => "Parge Lenis die ..." , "score" => 0, "time" => "05:51:23"),
            array("index" => 2, "name" => "jiengels" , "score" => 0, "time" => "05:51:18"),
            array("index" => 3, "name" => "n!n-oX" , "score" => 0, "time" => "05:47:27"),
            array("index" => 4, "name" => "Maraskan" , "score" => 0, "time" => "05:44:45"),
            array("index" => 5, "name" => "" , "score" => 0, "time" => "05:42:56"),
            array("index" => 6, "name" => "" , "score" => 0, "time" => "04:32:21"),
            array("index" => 7, "name" => "Heavy" , "score" => 0, "time" => "03:29:39"),
        ); 

$array_non_empty = array_filter($array, function($item){
    return (isset($item['name']) && $item['name']) ? TRUE : FALSE;
});

$count_non_empty = count($array_non_empty); // number of non-empty values

echo $count_non_empty;