简体   繁体   中英

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?

要对字符串中的多维数组访问进行插值,必须使用带有花括号的“复杂”格式。

echo "<tr><td>$item[k1]</td><td>$item[k2]</td><td>{$item['kTypes']['kType1']['desc']}</td><td>{$item['kTypes']['kType2']['desc']}</td>";

Try this foreach for your specific piece:

echo "<tr>";
foreach ($items as $field => $value) {
     if($field =='ktype'} {
           foreach($items['ktype'] as $ktype) {
                 foreach($ktype as $k) {
                      echo "<td>{$k}</td>";
                 }
           }
     } else {
          echo "<td>{$value}</td>";
     }
}
echo "</tr>";

However, I would do a recursive piece so it can go as deep into the array as possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM