如何在php中计算JSON值的长度?

时间:2019-05-26 21:18:25

标签: php json

我有一个 JSON,如下所示,我要通过php计算posts_id_en中有多少个值。目前为7,如下所示:

{
    "posts_id_en": "149968, 149939, 149883, 149877, 149876, 149847, 154303",
    "posts_id_fr": "149974,149953,149926, 149920, 149901",
    "episode_status": "3"
}

在执行echo $data->{"posts_id_en"};的php代码中,它显示如下所示的值:

149968, 149939, 149883, 149877, 149876, 149847, 154303

问题陈述:

我想知道我需要使用什么php代码,以便我们可以计算在posts_id_en中输入的值的数量。此时,如上所示输入7。

3 个答案:

答案 0 :(得分:4)

您要计数的项目在单个字符串中。首先,您必须将字符串分成多个项目,然后才能对它们进行计数。

将json放入一个php数组中

$jsonData = '{
    "posts_id_en": "149968, 149939, 149883, 149877, 149876, 149847, 154303",
    "posts_id_fr": "149974,149953,149926, 149920, 149901",
    "episode_status": "3"
}';
$data = json_decode($jsonData, true);

然后用分隔符“,”

分割字符串
$items = explode(", ", $data['posts_id_en']);

然后计数

echo count($items);

答案 1 :(得分:1)

<?php

$json = '{
    "posts_id_en": "149968, 149939, 149883, 149877, 149876, 149847, 154303",
    "posts_id_fr": "149974,149953,149926, 149920, 149901",
    "episode_status": "3"
}';
$decoded = json_decode($json, true);
$post_id = $decoded['posts_id_en'];

$resultList = [];
foreach($decoded as $key => $entry) {
    $everyNumberAsArray = explode(',', $entry);    
    $count = count($everyNumberAsArray);
    $resultList[$key] = $count;
}

var_export($resultList);

给出输出:

array (
  'posts_id_en' => 7,
  'posts_id_fr' => 5,
  'episode_status' => 1,
)

要获取特定值,可以通过以下方式使用它们:

echo $resultList['posts_id_en'] . '<br>' . PHP_EOL;

为您提供:

7

答案 2 :(得分:1)

一种简单的方法是,我们首先json_decode,然后验证所需属性中的数字并计算匹配项:

$str = '{
    "posts_id_en": "149968, 149939, 149883, 149877, 149876, 149847, 154303",
    "posts_id_fr": "149974,149953,149926, 149920, 149901",
    "episode_status": "3"
}';

$str_array = json_decode($str, true);

preg_match_all('/(\d+)/s', $str_array["posts_id_en"], $matches);

echo sizeof($matches[0]);

输出

7