在表,键和值中打印多维数组

时间:2020-07-04 20:21:57

标签: php multidimensional-array

我有以下数组

$consulta2 = Array ( 
                    [AB] => Array ( [0] => Noah [1] => 48 ) 
                    [BC] => Array ( [0] => Jacob [1] => 42 ) 
                    [DA] => Array ( [0] => Mason [1] => 27 )
                   )

我想在表中打印包含KEYS和VALUES的数组

我目前正在使用此foreach循环

foreach ($consulta2 as $key => $value){
        foreach ($value as $k => $v) {
          $template.= '<tr>
          <td class="service">'.$key.'</td>
          <td class="desc">'.$v.'</td> \r \n
          <td class="service">'.$v.'</td>
          <td class="service"></td>
          </tr>';
        }
    }

我正在得到下表

+-----+-------+-------+
| Key | Value | Value |
+-----+-------+-------+
|  AB |  Noah |  Noah |
+-----+-------+-------+
|  AB |   48  |   48  |
+-----+-------+-------+
|  BC | Jacob | Jacob |
+-----+-------+-------+
|  BC |   42  |   42  |
+-----+-------+-------+
|  DA | Mason | Mason |
+-----+-------+-------+
|  DA |   27  |   27  |
+-----+-------+-------+

但是我希望它看起来像这样

+-----+-------+-------+
| Key | Value | Value |
+-----+-------+-------+
|  AB |  Noah |   48  |
+-----+-------+-------+
|  BC | Jacob |   42  |
+-----+-------+-------+
|  DA | Mason |   27  |
+-----+-------+-------+

如果有人知道如何解决它,我将非常感激

1 个答案:

答案 0 :(得分:0)

删除内部循环并通过键($value0)访问1的项目:

foreach ($consulta2 as $key => $value){
    $template.= '<tr>
          <td class="service">'.$key.'</td>
          <td class="desc">'.$value[0].'</td> \r \n
          <td class="service">'.$value[1].'</td>
          <td class="service"></td>
          </tr>';
}