duanmiao6695 2015-11-22 17:22
浏览 23
已采纳

php - 从密钥名称获取JSON值

I have a JSON similar to the following:

{
    "name": "Activities",
    "description": "Activities",
    "parent_group_id": 0,
    "display": "Activities",
    "group_id": 7,
    "stamps": [
        {
            "stamp_id": 14,
            "name": "Stamp 14",
            "rank": 2
        },
        {
            "stamp_id": 20,
            "name": "Stamp 20",
            "rank": 4
        }
    ]
},
{
    "name": "Games",
    "description": "Games",
    "parent_group_id": 0,
    "display": "Games",
    "group_id": 6,
    "stamps": [
        {
            "stamp_id": 33,
            "name": "Stamp 33",
            "rank": 3
        },
        {
            "stamp_id": 31,
            "name": "Stamp 31",
            "rank": 1
        }
    ]
}

I want to get a list of each of the stamp_ids seperated by commas through PHP (eg. 14,20,33,31)

I have already tried this, with no luck:

$stampsdata     = json_decode($stampsjson, true);
$numberofstamps = $stampsdata['stamps']['stamp_id']);

Can anyone help?

  • 写回答

1条回答 默认 最新

  • douyao7390 2015-11-22 17:31
    关注

    decode the JSON with json_decode and use array_column to get the IDs.

    working solution:

    // true needed to transform object to associative array
    // $json contains your JSON string
    
    $data = json_decode($json, true);
    
    $stamps = [];
    foreach ($data as $obj) {
        $stamps[] = array_column($obj['stamps'], 'stamp_id');
    }
    
    // implode sub arrays and concatenate string
    $str = '';
    
    foreach ($stamps as $stamp) {
        $sub = implode(',', $stamp);
        $str .= $sub . ',';
    }
    
    // remove trailing comma
    $stampIds = rtrim($str, ',');
    print ($stampIds);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!