0

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"
}
]
}
2
  • In PHP JSON, map keys must be enclosed with "", or syntax error would be thrown. Commented Feb 23, 2016 at 10:46
  • Show us the code you have. Include the variable assignment to which you assign the JSON. And include the structure you expect to have as a result. Commented Feb 23, 2016 at 10:48

2 Answers 2

2

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',
)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.