计算数组中key的值

Count value of key in array

我有这个数组:

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_filter 仅过滤出所需的数组详细信息,并计算它的数量。

这可能是最简单的,也是性能导向的,因为它不会循环。

为了好玩:

$count = array_count_values(array_column($array, 'publish'))[1];
  • 获取 publish 个键的数组
  • 计算值
  • 使用索引 [1]
  • 获取 1 的计数

O.K。更多乐趣:

$count = count(array_keys(array_column($array, 'publish'), 1));
  • 获取 publish 个键的数组
  • 获取值为1
  • 的数组键
  • 计算数组

注意:为了更准确,您可能希望将 true 作为第三个参数传递给 array_keys(),并使用 '1' 而不是1 如果 1 是字符串而不是整数。