andrea444 andrea444 - 1 year ago 88
JSON Question

JSON array in html table

I have a json array, looks like:

Array (
[0] => Array
[k1] => aaa
[k2] => aaa
[kTypes] => Array
[ktype1] => Array
[desc] => asd

[ktype2] => Array
[desc] => asd



And I try to get the desc values inside ktypes, tried this:

$items = $myArray;
// echo "<pre>";
// print_r($items);
// echo "</pre>";

echo '<table>';
echo '<tr><th>k1</th><th>k2</th><th>ktype1</th><th>ktype2</th></tr>';
foreach($items as $item)
echo "<tr><td>$item[k1]</td><td>$item[k2]</td><td>$item[kTypes][kType1][desc]</td><td>$item[kTypes][kType2][desc]</td>";
echo '</table>';

which works fine for the first both columns, but not the ktype ones. There the:

echo is "Array[kType2][desc]"

So I tried a nested loop, but this didn't work, too.

can anyone help me on the right track?

Answer Source

To interpolate multidimensional array accesses in a string, you have to use the "complex" format with curly braces.

echo "<tr><td>$item[k1]</td><td>$item[k2]</td><td>{$item['kTypes']['kType1']['desc']}</td><td>{$item['kTypes']['kType2']['desc']}</td>";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download