我有这个数组:
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
的宽度。
最佳答案
为了好玩:
$count = array_count_values(array_column($array, 'publish'))[1];
- 获取
publish
键的数组 - 计算值
- 使用索引
[1]
获取1
的个数
好的。更多乐趣:
$count = count(array_keys(array_column($array, 'publish'), 1));
- 获取
publish
键的数组 - 获取值为
1
的数组键值 - 对数组进行计数
注意:您可能希望将 true
作为第三个参数传递给 array_keys()
以更加准确并使用 '如果
而不是 1
是字符串而不是整数,则为 1'1
。
关于php - 计算数组中key的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36480857/