php - 计算数组中key的值

标签 php arrays count predicate

我有这个数组:

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/

相关文章:

php - 多维数组将每个列表数组存储在另一个数组中

python - 计算循环的结果?

mysql 哪里或有

php - 如何检查我的 SQL 表中是否存在数据以及它是否不插入更新的数据?

php - 通过 cron 运行 php 脚本,如何记录任何输出?

php - 日期时间列的平均值

Java Android 使用无键 JSON 对象迭代 JSON 数组

arrays - 在 Spark Scala Dataframe 中迭代具有动态大小的数组列

function - 数学: get number of arguments passed to a function?

php - 如何从 PHP 脚本调用 ASP.NET .dll 文件?