Joe Joe - 7 months ago 22
PHP Question

How to output these values in a list from PHP - array_keys()?

I'm having trouble trying to output array values into separate list items like so:


  • 1993 Mercedes Benze Own

  • 2006 Honda Fit Lease



. Here's the output by
print_r($array)
:

Array
(
[0] => [{"Year":"1993","Make":"Mercedes","Model":"Benz","Lease / Own":"Own"},{"Year":"2016","Make":"Honda","Model":"Fit","Lease / Own":"Lease"}]
)


However, the format is tricky for me and I'm not exactly sure where I should go from here in order to output the values when they are laid out like this.

I know it has to do with
array_keys()
, but I'm lost as to where to go from here since the following gives me nothing:

print_r(array_keys($array));


Any clues to point me in the right direction?

Answer

Nothing you've shown has anything to do with array_keys(). First thing is decode the 0 index of your array that is JSON:

$result = json_decode($array[0], true);

Then loop through it:

foreach($result as $value) {
    echo "{$value['Year']} {$value['Make']} {$value['Model']} {$value['Lease / Own']}<br>\n";
}

If you need the keys (Year, Make, Model, Lease / Own) as column headings or whatever then you can use array keys on the first row of the result:

foreach(array_keys($result[0]) as $heading) {
    echo "$heading<br>\n";
}
Comments