簡體   English   中英

使用php從json數組中選擇一個對象

[英]Selecting an object from json array using php

嗨,我有這個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"
}
]
}

這樣,您可以從給定的json中提取ID:

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

首先,您需要修復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',
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM