【问题标题】:JSON array in html tablehtml表中的JSON数组
【发布时间】:2013-11-14 07:29:54
【问题描述】:

我有一个 json 数组,看起来像:

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

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

            )

    )

我尝试获取 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>';   

这对前两列都有效,但不适用于 ktype 列。那里:

echo is "Array[kType2][desc]" 

所以我尝试了一个嵌套循环,但这也没有用。

谁能帮助我走上正确的道路?

【问题讨论】:

  • 你为什么还要使用循环?循环将遍历您的数组,因此 $item 将是 $items[k1] 在开始,下一个 $items[k2] 等等...
  • @Rsauxil 我想你没有注意到顶部的[0]。它是一个索引数组,其元素是关联数组。
  • @barmar:没错。

标签: php arrays json foreach html-table


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    为您的特定作品尝试这个 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>";
    

    但是,我会做一个递归部分,以便它可以尽可能深入到数组中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-02
      • 2014-06-16
      • 1970-01-01
      • 2021-09-06
      • 2014-08-02
      • 1970-01-01
      • 1970-01-01
      • 2020-05-27
      相关资源
      最近更新 更多