【问题标题】:How to calculate the length of JSON values in php?如何计算 php 中 JSON 值的长度?
【发布时间】:2019-10-12 12:28:00
【问题描述】:

我有一个 如下所示的 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如上图。

【问题讨论】:

标签: php json


【解决方案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

【讨论】:

    【解决方案2】:

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

    把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);
    

    【讨论】:

    • 我的问题有一个小错误。我稍微修改了我的问题。
    • 我已经更新了对你的新 json 的回答 - 但没关系。
    • 我还有一个question。它不相似。我想知道你是否可以看看。
    【解决方案3】:
    <?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
    

    【讨论】:

    • 在我回答问题时打败了我:P
    • @Jimmix 我已经更新了我的问题。我的问题有一个小错误。
    • @Alo 我上次不够小心所以你做了that:P
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    • 1970-01-01
    • 2013-02-18
    • 1970-01-01
    • 1970-01-01
    • 2014-07-07
    • 1970-01-01
    相关资源
    最近更新 更多