hemanth kumar
hemanth kumar

Reputation: 539

Selecting an object from json array using php

Hi I have this Json array, I want to select only id in php,. Please help. I want to select only id in php,. Please help

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

Upvotes: 0

Views: 859

Answers (2)

trincot
trincot

Reputation: 350770

First you need to fix the JSON. Key names must be enclosed in double quotation marks, like this:

$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"
        }
    ]
}';

Once you have that, you can extract the array with id values as follows:

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

If you are with PHP < 5.5 then replace that last line with:

$ids = array_map(function ($rec) { return $rec["id"]; }, $arr["records"]);

$ids will be the following array:

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

Upvotes: 2

Maha Dev
Maha Dev

Reputation: 3965

This way you can extract id from given json:

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

Upvotes: 1

Related Questions