Being able to quickly or efficiently get the keys from an array which is most likely an API call is great. You can see what data exists which may not be clear in the docs (if they exist).
Here is a method with PHP to print out an array keys and values, you can even shape the loop to create a CREATE TABLE query using the keys for column names or even creating an INSERT query.
This example i am using the Reddit API, this is a multi dimensional array and you can see for the foreach i further define the row for which i want to get the keys and values for.
Printing array keys & values
The basic code with no formatting or style is:
<?php $data = json_decode(file_get_contents("http://www.reddit.com/r/pics/c1wqkk.json"), true); foreach ($data[0]['data']['children'][0]['data'] as $key => $value) { echo "$key : $value<br>"; }
[0]['data']['children'][0]['data']
points to the part with the keys i am after. Load up the http://www.reddit.com/r/pics/c1wqkk.json
call in a json formatter to see multi dimensions to this call.
If you run the code above you will notice a few errors for trying to parse arrays, that is because there is still another layer (dimension) you can go into. However these are mostly always empty for this call.
The booleans also do not get displayed (true and false), nor empty strings (“”).
Formatting and adding style
To add some formatting to display the values accurately for their type here is an added function plus a little bit of CSS to make readability better:
<style> body { background: #0b1034; } p { color: #eca835; display: inline; } .key { color: #9f8fe2; } .value { color: #8fcbe2; } </style> <?php function format_value_type($var) { if (is_array($var)) { return 'Array[]'; } elseif (is_null($var)) { return "NULL"; } elseif ($var === '') { return '""'; } elseif ($var === true) { return 'true'; } elseif ($var === false) { return 'false'; } else { return $var; } } $data = json_decode(file_get_contents("http://www.reddit.com/r/pics/c1wqkk.json"), true); foreach ($data[0]['data']['children'][0]['data'] as $key => $value) { echo "<p class='key'>$key</p> <p>:</p> <p class='value'>" . format_value_type($value) . "</p><br>"; }
This looks like