使用php从json数组中选择一个对象

时间:2016-02-23 10:38:08

标签: php arrays json

嗨我有这个Json数组, 我想在php中只选择id。请帮忙。 我想在php中只选择id。请帮忙

{
next_offset: -1,
records: [
{
my_favorite: false,
following: false,
id: "61a55092-5683-1088-2d6c-56c99c5d4873",
name: "2A Unit",
lease: "",
unit_floor: 2,
_acl: {
fields: { }
},
_module: "SREV1_Unit"
},
{
my_favorite: false,
following: false,
id: "87dad127-a60e-15a3-148e-56c7675f11df",
name: "1A",
lease: "",
unit_floor: 1,
_acl: {
fields: { }
},
_module: "SREV1_Unit"
}
]
}

2 个答案:

答案 0 :(得分:1)

这样你就可以从给定的json中提取id:

$post_data = json_decode(your_json, true);
foreach ($post_data['records'] as $record){
    echo $record['id'];
}

答案 1 :(得分:1)

首先,您需要修复JSON。键名必须用双引号括起来,如下所示:

$json = '{
    "next_offset": -1,
    "records": [
        {
            "my_favorite": false,
            "following": false,
            "id": "61a55092-5683-1088-2d6c-56c99c5d4873",
            "name": "2A Unit",
            "lease": "",
            "unit_floor": 2,
            "_acl": {
                "fields": { }
            },
            "_module": "SREV1_Unit"
        },
        {
            "my_favorite": false,
            "following": false,
            "id": "87dad127-a60e-15a3-148e-56c7675f11df",
            "name": "1A",
            "lease": "",
            "unit_floor": 1,
            "_acl": {
                "fields": { }
            },
            "_module": "SREV1_Unit"
        }
    ]
}';

完成后,您可以使用 id 值提取数组,如下所示:

$arr = json_decode($json, true);
$ids = array_column($arr["records"], "id"); // requires PHP >= 5.5

如果您使用PHP< 5.5然后用:

替换最后一行
$ids = array_map(function ($rec) { return $rec["id"]; }, $arr["records"]);

$ ids 将是以下数组:

array (
  0 => '61a55092-5683-1088-2d6c-56c99c5d4873',
  1 => '87dad127-a60e-15a3-148e-56c7675f11df',
)