Ethan Allen Ethan Allen - 1 month ago 9
JSON Question

How do I get all the keys in JSON within PHP?

How do I get all of the keys and loop through them, echoing each one, from a JSON object array?

Here is my code:

/* SAMPLE JSON THAT IS SENT
$mystring = '{
"display_name": "Silverware",
"fields": [
{
"field_name": "Age",
"sort_order": 1,
"required": 0,
"view_type": "text",
"description": "",
"multi_value": 0,
"char_count": 255
},
{
"field_name": "Brand",
"sort_order": 2,
"required": 0,
"view_type": "multiselect",
"description": "",
"multi_value": 1,
"char_count": 255
}
]
}';
*/


$json = json_decode($HTTP_RAW_POST_DATA);
$arr = $json->{'fields'};

// This is how I print a specific value
//print $arr[0]->{'field_name'};


Adding the following isn't working for me:

foreach ($arr as $k => $v) {
echo $k', ';
}

Answer

Use true for the second parameter of json_decode().

foreach ($j['fields'] as $field) {
  $keys = array_keys($field);
  foreach ($keys as $key) {
    echo $key;
  }
}