PHP-在数组中计算匹配数组
我有一个数组结构,如下所示:PHP-在数组中计算匹配数组,php,arrays,Php,Arrays,我有一个数组结构,如下所示: Array ( [0] => Array ( [type] => image [data] => Array ( [id] => 1 [alias] => test [caption] => no ca
Array
(
[0] => Array
(
[type] => image
[data] => Array
(
[id] => 1
[alias] => test
[caption] => no caption
[width] => 200
[height] => 200
)
)
[1] => Array
(
[type] => image
[data] => Array
(
[id] => 2
[alias] => test2
[caption] => hello there
[width] => 150
[height] => 150
)
)
)
$result = countArray($array, 'type', 'image');
我的问题是,如何计算将其类型设置为image(或其他相关内容)的嵌入式阵列的数量?实际上,该值可能会有所不同
上面的数组会给我一个2的答案
多亏了最简单的方法就是循环所有子数组并检查它们的类型,如果计数器与所需类型匹配,则递增计数器
$count = 0;
foreach ( $myarray as $child ){
if ( $child['type'] == 'image' ){
$count++;
}
}
如果您有PHP5.3.0或更高版本,您可以使用array_reduce(未经测试):
这两者都可以移动到返回$count
的函数中,该函数允许您指定要计数的类型。例如:
function countTypes(array $haystack, $type){
$count = 0;
foreach ( $haystack as $child ){
if ( $child['type'] == $type ){
$count++;
}
}
return $count;
}
正如您从其他答案中看到的,您可以进行更多的错误检查,但是您没有说什么是不可能的(您希望使用assert
)
可能的错误有:
- 子对象不是数组
- 孩子没有设置
键类型
如果你的数组总是像你的例子那样设置,那么无声地失败(通过在If语句中加一个检查)将是一个坏主意,因为它会掩盖程序中其他地方的错误。你必须迭代数组中的每个元素,并检查元素是否符合你的条件:
$data = array(...);
$count = 0;
foreach ($data as $item) {
if ('image' === $item['type']) {
$count++;
}
}
var_dump($count);
试试这个:
function countArray(array $arr, $arg, $filterValue)
{
$count = 0;
foreach ($arr as $elem)
{
if (is_array($elem) &&
isset($elem[$arg]) &&
$elem[$arg] == $filterValue)
$count++;
}
return $count;
}
例如,您可以这样称呼它:
Array
(
[0] => Array
(
[type] => image
[data] => Array
(
[id] => 1
[alias] => test
[caption] => no caption
[width] => 200
[height] => 200
)
)
[1] => Array
(
[type] => image
[data] => Array
(
[id] => 2
[alias] => test2
[caption] => hello there
[width] => 150
[height] => 150
)
)
)
$result = countArray($array, 'type', 'image');
除了Yacoby的答案之外,如果您使用的是PHP 5.3,您还可以通过闭包实现功能性风格:
$count = 0;
array_walk($array, function($item)
{
if ($item['type'] == 'image')
{
$count++;
}
});
如果未设置
$elem[$arg]
,则它将不等于$filter
,因此检查有点冗余,是吗?您还将$filterValue
而不是$filter
。感谢您的输入错误。不过,我不太清楚另一件事——我相信在某些系统上你会得到警告……谢谢——每个人都给出了很多很好的答案!