简体   繁体   English

HTML表中的JSON数组

[英]JSON array in html table

I have a json array, looks like: 我有一个json数组,看起来像:

 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: 我尝试在ktypes中获取desc值,尝试了以下方法:

$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. 这对前两列都适用,但对ktype而言则无效。 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: 为您的特定作品尝试以下foreach方法:

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. 但是,我会做一个递归操作,以便它可以尽可能深入到数组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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