如何计算 JSON 对象中存在的元素数量?

How to count the number of elements present in a JSON object?

我有一个 PHP/JSON 如下所示。

JSON:

{"posts_id_en":"101, 102, 103","posts_id_fr":"", "reports_id_en":"101, 102", "reports_id_fr":"101"}

PHP代码:

echo count(explode(",", $data->posts_id_en));    //  Line A  (3)

echo count(explode(",", $data->posts_id_fr));    // Line B   (1)

echo count(explode(",", $data->reports_id_en));    // Line C  (2)

echo count(explode(",", $data->reports_id_fr));    // Line D  (1)

A行php代码,C行php代码和D行php代码打印321 .

问题陈述:

我想知道我需要对上面 B 行的 php 代码进行哪些更改,以便它打印 0,因为 posts_id_fr

中没有元素

您只需确保该数组中没有空值。因为当空字符串被展开时,它会创建一个值为空的元素。

使用 array_filter

删除这些值
echo count(array_filter(explode(",", $data->posts_id_fr)));

// Will print 0

以防万一你想按照GrumpyCrouton

的建议循环
foreach($data as $key => $value)
{
  echo $key . ' : ' . count(array_filter(explode(",", $value))) . PHP_EOL;
}

Output:
posts_id_en : 3
posts_id_fr : 0 
reports_id_en: 2
reports_id_fr: 1

您必须在尝试使用该值之前检查该值是否已设置

$str = '{"posts_id_en":"101, 102, 103","posts_id_fr":"", "reports_id_en":"101, 102", "reports_id_fr":"101"}';

$obj = json_decode($str);

foreach ( $obj as $o=>$v) {
    echo $o . ' ';
    echo strlen($v) > 0 ? count(explode(",", $v)) : 0 ;
    echo PHP_EOL;
}

结果

posts_id_en 3
posts_id_fr 0
reports_id_en 2
reports_id_fr 1

此处略有变化,您可以使用 preg_split 并使用标志忽略空拆分。我们在 non-digits.

上拆分
<?php

$str = '{"posts_id_en":"101, 102, 103","posts_id_fr":"", "reports_id_en":"101, 102", "reports_id_fr":"101"}';
$arr = json_decode($str, true);

$arr = array_map(function($item) {
    $nums = preg_split('/[^0-9]/', $item, -1, PREG_SPLIT_NO_EMPTY);

    return $nums;
}, $arr);

var_export($arr);

$arr = array_map('count', $arr);

var_export($arr);

输出:

array (
  'posts_id_en' => 
  array (
    0 => '101',
    1 => '102',
    2 => '103',
  ),
  'posts_id_fr' => 
  array (
  ),
  'reports_id_en' => 
  array (
    0 => '101',
    1 => '102',
  ),
  'reports_id_fr' => 
  array (
    0 => '101',
  ),
)array (
  'posts_id_en' => 3,
  'posts_id_fr' => 0,
  'reports_id_en' => 2,
  'reports_id_fr' => 1,
)

包含中间步骤,因此您可以看到 preg_split 的结果。

echo count(preg_split("/,/", $data->posts_id_fr,-1, PREG_SPLIT_NO_EMPTY));