[英]count sub-elements of an array in php
I have a 2 dimensional array in PHP that looks like this: 我在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
)
)
I want to determine how many items in my array don't have a description. 我想确定数组中没有描述的项目。
The function I've got so far looks like the below ... 到目前为止,我拥有的功能如下所示……
function array_count ($array, $key) {
// count($array[*][$key])
$c = 0;
foreach ($array as $i=>$subarray) {
$c += ($subarray[$key]!='');
}
return $c;
}
... is there a better way to do this? ... 有一个更好的方法吗?
... how would I extend this to count for matches against a value, like $array[*][is_active]=='Y'
...我将如何扩展它以对一个值进行匹配计数,例如
$array[*][is_active]=='Y'
I'm thinking this might work: 我想这可能工作:
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;
}
This way I can do the following: 这样,我可以执行以下操作:
// 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
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;
}
checking empty array: 检查空数组:
if( 0 < ( $cnt = count($array) ) )
{
echo "Your array size is: $cnt";
}
else
echo "Too bad, your array is empty :(";
use:- 采用:-
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>";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.