0

我在 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

4 回答 4

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
于 2012-11-11T09:19:44.427 回答
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;
}
于 2012-11-11T08:35:02.027 回答
0

检查空数组:

if( 0 < ( $cnt = count($array) ) )
{
 echo "Your array size is: $cnt";
}
else
 echo "Too bad, your array is empty :(";
于 2012-11-11T08:59:48.523 回答
-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>";

    }
于 2012-11-11T08:34:03.683 回答