猿问

如何计算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"

}

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


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

问题陈述:


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


料青山看我应如是
浏览 417回答 3
3回答

慕桂英546537

您尝试计算的项目位于单个字符串中。首先,您必须将字符串分成多个项目,然后您才能对其进行计数。获取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);

皈依舞

<?php$json = '{&nbsp; &nbsp; "posts_id_en": "149968, 149939, 149883, 149877, 149876, 149847, 154303",&nbsp; &nbsp; "posts_id_fr": "149974,149953,149926, 149920, 149901",&nbsp; &nbsp; "episode_status": "3"}';$decoded = json_decode($json, true);$post_id = $decoded['posts_id_en'];$resultList = [];foreach($decoded as $key => $entry) {&nbsp; &nbsp; $everyNumberAsArray = explode(',', $entry);&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; $count = count($everyNumberAsArray);&nbsp; &nbsp; $resultList[$key] = $count;}var_export($resultList);给出输出:array (&nbsp; 'posts_id_en' => 7,&nbsp; 'posts_id_fr' => 5,&nbsp; 'episode_status' => 1,)要获得特定值,您可以通过以下方式使用它们:echo $resultList['posts_id_en'] . '<br>' . PHP_EOL;这给你:7

慕斯王

一种简单的方法是,我们首先json_decode验证所需属性中的数字,并计算匹配项:$str = '{&nbsp; &nbsp; "posts_id_en": "149968, 149939, 149883, 149877, 149876, 149847, 154303",&nbsp; &nbsp; "posts_id_fr": "149974,149953,149926, 149920, 149901",&nbsp; &nbsp; "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
随时随地看视频慕课网APP
我要回答