如何使用PHP将此JSON数据添加到HTML表中

时间:2016-10-14 06:15:15

标签: php json

我已经知道如何连接到数据库以及所有这些。我只需要知道我需要什么样的PHP循环来正确获取这些数据

以下是JSON示例:

[equipment] => Array
    (
        [0] => Array
            (
                [id] => 401582887101
                [name] => Driver Seat
                [equipmentType] => OTHER
                [availability] => STANDARD
                [attributes] => Array
                    (
                        [0] => Array
                            (
                                [name] => Number Of Driver Seat Manual Adjustments
                                [value] => 6
                            )

                        [1] => Array
                            (
                                [name] => Height Adjustable Driver Seat
                                [value] => height adjustable
                            )

                    )

            )

这就是我想要的表格:

id  name    equipmentType   availibility    attribute name  attribute value

401582887101驾驶员座椅其他标准驾驶员座椅数量手动调节6 401582887101驾驶员座椅其他标准高度可调驾驶员座椅高度可调

1 个答案:

答案 0 :(得分:1)

它有点丑陋的代码,但它适用于您的情况,只要数组的数据结构保持不变:

echo '<table border="1">';
echo '<thead><th>id</th><th>name</th><th>equipmentType</th><th>availibility</th><th>attribute name</th><th>attribute value</th></thead>';
foreach ($data['equipment'] as $equipment) {
    $row = '<tr>';
    foreach($equipment as $key => $item) {
        if(is_array($item)) {
            foreach ($item as $attribute) {
                $attributeStr = '';
                $attributeStr .= '<td>'.$attribute['name'].'</td>';
                $attributeStr .= '<td>'.$attribute['value'].'</td>';
                echo $row.$attributeStr.'</tr>';
            }
        }
        else {
            $row .= '<td>'.$item.'</td>';
        }
    }
}
echo '</table>';