-2

I'm using Laravel. I have JSON returned from Database. I would like to get key names like "id / name / email / revision" from following JSON.

{
    "id": "000",
    "records": [
        {
            "id": 23,
            "name": "hoge",
            "email": "Hoge@alk.jp",
            "revision": 0
        },
        {
            "id": 24,
            "name": "zaku",
            "email": "zaku@alk.jp",
            "revision": 0
        },
    ]
}

Please let me know how to get key names. Thank you.

tajihiro
  • 2,293
  • 7
  • 39
  • 60

2 Answers2

2

You should get the keys with collection get key by code following:

collect($data->records)->keys();

This will return

id
name
email
revision

More detail you can check here: https://laravel.com/docs/8.x/collections#method-keys

Sok Chanty
  • 1,678
  • 2
  • 12
  • 22
1

Use json_decode to convert it to an array:

$array = josn_decode($jsonVariable, true);

Then use foreach:

foreach($array['records'][0] as $key => $value){
    $keys[] = $key;
}

or array_keys:

array_keys($array['records']);

or collect to get keys:

$keys = collect($array['records'])->keys();
N. Bien
  • 19
  • 4