Php 数组中键的计数值
我有这个阵列:Php 数组中键的计数值,php,arrays,count,predicate,Php,Arrays,Count,Predicate,我有这个阵列: Array ( [boks_1] => Array ( [tittel] => Test [innhold] => This is a test text [publish] => 2 ) [boks_2] => Array ( [tittel] => Te
Array
(
[boks_1] => Array
(
[tittel] => Test
[innhold] => This is a test text
[publish] => 2
)
[boks_2] => Array
(
[tittel] => Test 3
[innhold] => This is a text test
[publish] => 1
)
[boks_3] => Array
(
[tittel] => Kontakt oss
[innhold] => This is a test text
[publish] => 1
)
)
如何使用PHP
count()
来计算数组中出现了多少次[publish]=>1
?我将使用该值来控制flexbox容器中divs
的宽度 这应该可以解决您的问题:
$array = array(); //This is your data sample
$counter = 0; //This is your counter
foreach ($array as $key => $elem) {
if (array_key_exists('publish', $elem) && $elem['publish'] === 1) {
$counter += $elem['publish'];
}
}
希望这能有所帮助
$newArray = array_filter($booksArray, function($bookDet) { if($bookDet["publish"]==1) { return $bookDet; } });
$getCount = count($newArray);
使用array\u filter
仅过滤出所需的数组详细信息,并获取其计数
这可能是最简单的,也是面向性能的,因为它不会循环。为了好玩:
$count = array_count_values(array_column($array, 'publish'))[1];
- 获取
键的数组publish
- 计算数值
- 使用索引获取
s的计数1
[1]
$count = count(array_keys(array_column($array, 'publish'), 1));
- 获取
键的数组publish
- 获取值为
1
- 数一数数组
注意:如果
1
是字符串而不是整数,您可能希望将true
作为第三个参数传递给array_keys()
,以便更准确地使用'1'
而不是1
。您不能简单地使用count()
函数,你需要在数组中循环并增加一个计数器。问题出错了,OP询问的是publish==1的特定计数是的,我忘记了条件,所以我更新了;)。但是您的解决方案比我的更简洁。在newArray var之前有双$sign,它将始终返回0(零)作为计数。array\u filter()
很好,但是=
将返回true
和一些字符串。可能是函数($v){return$v['publish']==1;}
或者如果字符串===1'
。中的,1)
在做什么?我在文档中没有看到它有第二个参数?那应该是array\u column()
我想?所以array\u column($array,'publish',1)
而不是array\u column($array,'publish'),1)
?“@Rasclatt:那是一个打字错误,被删除了。是的,我想了很多,但我想我会问一下,万一这是我不知道的遗留问题,我从其他人的答案中学到了很多,比如array\u column()
,例如,我通常使用循环来完成相同的任务,所以现在我知道得更多了!自从你把我叫回来后,增加了更多的乐趣:-)这可能就是早期的,1)
的来源。