php - 从密钥名称获取JSON值

时间:2015-11-22 17:22:45

标签: php json

我有一个类似于以下内容的JSON:

    <div ng-repeat="str in myData">{{str.id}}. {{str.string}}</div>
    <br/> 
    <span ng-if="count >= 1" style="color:red;">One or more string is empty</span>
    </div>

我想获得一个通过PHP用逗号分隔的每个stamp_id的列表(例如14,20,33,31)

我已经尝试过这个,没有运气:

{
    "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
        }
    ]
}

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:3)

使用json_decode解码JSON并使用https://github.com/activerecord-hackery/ransack/pull/390获取ID。

工作解决方案:

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