在php中计算数组的子元素

时间:2012-11-11 08:19:54

标签: php arrays function

我在PHP中有一个二维数组,如下所示:

Array (
[0] => Array
    (
        [id] => 205
        [name] => Data Export
        [description] => A function to export survey results.
        [is_active] => Y
    )

...

[99] => Array
    (
        [id] => 206
        [name] => Data Import
        [description] => 
        [is_active] => N
    )
)

我想确定数组中有多少项没有描述。

到目前为止,我所获得的功能如下所示......

function array_count ($array, $key) {
    // count($array[*][$key])
    $c = 0;
    foreach ($array as $i=>$subarray) {
        $c += ($subarray[$key]!='');
    }
    return $c;
}

......有更好的方法吗?

...我将如何扩展此值以计算与$array[*][is_active]=='Y'

之类的值匹配

4 个答案:

答案 0 :(得分:2)

我认为这可行:

function array_count ($array, $key, $value = NULL) {
    // count($array[*][$key])
    $c = 0;
    if (is_null($value)) {
        foreach ($array as $i=>$subarray) {
            $c += ($subarray[$key]!='');
        }
    } else {
        foreach ($array as $i=>$subarray) {
            $c += ($subarray[$key]==$value);
        }
    }
    return $c;
}

这样我可以做到以下几点:

// assume $foo is an array of 100 arrays, 
// of which 20 sub-arrays have a blank 'description', 
// and 35 have 'is_active' set to 'Y' and 65 set to 'N'

echo array_count ($foo, 'description'); // ... 80 non-blanks
echo array_count ($foo, 'is_active'); // ... 100 non-blanks
echo array_count ($foo, 'is_active', 'Y'); // ... 35 matches
echo array_count ($foo, 'description', ''); // ... 20 is-blanks

答案 1 :(得分:1)

function array_count ($array, $key, $value) {
    // count($array[*][$key])
    $c = 0;
    foreach ($array as $i=>$subarray) {
        $c += strcmp( $subarray[$key], $value) ) === 0 ? 1 : 0;
    }
    return $c;
}

答案 2 :(得分:0)

检查空数组:

if( 0 < ( $cnt = count($array) ) )
{
 echo "Your array size is: $cnt";
}
else
 echo "Too bad, your array is empty :(";

答案 3 :(得分:-3)

使用: -

foreach ($array as $i=>$value) {


//from this you get the all whole array description value then apply if else condition to         short out

echo $_POST[$i]['description']."</br>";

    }