我有一个具有以下格式的数组:
Array
(
[0] => Array
(
[Push to Web] => Yes
[attribute_set] => laminate_flooring
[category] => Accessories/Underlay
[name] => Under Pad Feather Light Foam
[sku] => 123-1028
[description] => Floor Underlayment Feather Light (Vapour Barrier) 200 Sqft/Roll
[short_description] => Floor Underlayment Feather Light (Vapour Barrier) 200 Sqft/Roll
[image] => 123-1028.jpg
[gallery_Image] => 9095307460638-424-424.jpg
[price] => 0.24
[qty_ca] => 16
[weight] => 3
[meta_description] => 51-1001
[meta_title] => Under Pad Feather Light Foam
[status] => 1
[flooring_coverage] => 200
[is_flooring_product] => 1
[web_price_comparative] => 0.31
)
[1] => Array
(
[Push to Web] => Yes
[category] => Accessories
[name] => Vent Maple Flush 4x10
[sku] => 089-1000
[description] => Vent Flush Mount Maple 4 x 10
[short_description] => Vent Flush Mount Maple 4 x 10
[image] => 089-1000.jpg
[price] => 17.05
[qty_ca] => 63
[qty_us] => 41
[meta_description] => 10-1023
[meta_title] => Vent Maple Flush 4x10
[status] => 1
[flooring_coverage] => 1
[min_order_qty] => 400
[web_price_comparative] => 22.16
)
)
我必须打印表中的数据,以便将数组的每个键打印为列标题,将值打印为列数据。这意味着“推送到Web”,“ attribute_set等”将是标题,是的,“ ladder_flooring”将分别是数据。
我写了以下内容,但不起作用。
$row = 0;
$table = '<table border="1" id="datatable">';
foreach($data as $value){
$table .= '<tr>';
if ($row == 0) {
foreach($value as $innerkey=>$innervalue){
$table .= '<td>'.$innerkey.'</td>';
}
}
$table .= '</tr><tr>';
foreach($value as $innerkey=>$innervalue){
$table .= '<td>'.$innervalue.'</td>';
}
$table .= '</tr>';
$row++;
}
$table .= '</table>';
print_r($table);
表的输出应如下:
第一个问题是标题行仅在第一数据行中继续打印最多的数据。其次,如果任何数据单元不可用,则由下一个单元数据填充。但应该保留为银行牢房。请帮助我解决问题。在此先感谢
[此外,我添加了htmlentities只是为了阻止任何恶意html破坏表,但是如果您知道不需要它,可以将其删除。
$table = '<table border="1" id="datatable"><tr>';
// Get the headers from the first child array.
$headers = array_keys($data[0]);
foreach($headers as $header){
$table .= '<th>'.htmlentities($header).'</th>';
}
foreach($data as $value){
$table .= '</tr><tr>';
foreach($value as $innerkey=>$innervalue){
$table .= '<td>'.htmlentities($innervalue).'</td>';
}
$table .= '</tr>';
}
$table .= '</table>';