我有像下面这样的json数组:
Array
(
[total] => 1
[rows] => Array
(
[0] => Array
(
[date] => 2014-11-12
[A] => 1
[B] => 2
[C] => 2
[D] => No
[E] => New
[F] => New
[G] => 1
[H] => 1
[I] => 1
[A] => 1
[J] => 1
[B] => 1
)
[1] => Array
(
[date] => 2014-12-12
[A] => 1
[B] => 1
[C] => 2
[D] => No
[E] => New
[F] => New
[G] => 2
[H] => 2
[I] => 2
[A] => 2
[J] => 2
[B] => 2
)
)
)
我想回复如下:
date A B C D E F G H I A J B
2014-11-12 1 2 2 No New New 1 1 1 1 1 1
2014-12-12 1 1 2 No New New 2 2 2 2 2 2
我怎么做这件事最好的建议是什么。
答案 0 :(得分:1)
在这种情况下,您可以使用普通的foreach。至于标题,您可能需要使用array_keys()
。例如:
<?php
$array = [ 'total' => 1, 'rows' => [ [ 'date' => '2014-11-12', 'A' => '1', 'B' => '2', 'C' => '2', 'D' => 'No', 'E' => 'New', 'F' => 'New', 'G' => '1', 'H' => '1', 'I' => '1', 'A' => '1', 'J' => '1', 'B' => '1', ], [ 'date' => '2014-12-12', 'A' => '1', 'B' => '1', 'C' => '2', 'D' => 'No', 'E' => 'New', 'F' => 'New', 'G' => '2', 'H' => '2', 'I' => '2', 'A' => '2', 'J' => '2', 'B' => '2', ], ],];
$keys = array_keys(reset($array['rows']));
?>
<table cellpadding="10">
<thead>
<tr align="left">
<?php foreach($keys as $header): ?>
<th><?php echo $header; ?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php foreach($array['rows'] as $row): ?>
<tr><?php foreach ($row as $value): ?>
<td><?php echo $value; ?></td>
<?php endforeach; ?></tr>
<?php endforeach; ?>
</tbody>
</table>
以CSV格式打印:
$array = [ 'total' => 1, 'rows' => [ [ 'date' => '2014-11-12', 'A' => '1', 'B' => '2', 'C' => '2', 'D' => 'No', 'E' => 'New', 'F' => 'New', 'G' => '1', 'H' => '1', 'I' => '1', 'A' => '1', 'J' => '1', 'B' => '1', ], [ 'date' => '2014-12-12', 'A' => '1', 'B' => '1', 'C' => '2', 'D' => 'No', 'E' => 'New', 'F' => 'New', 'G' => '2', 'H' => '2', 'I' => '2', 'A' => '2', 'J' => '2', 'B' => '2', ], ],];
$data[] = array_keys(reset($array['rows'])); // push header inside
$data = array_merge($data, $array['rows']); // push values inside
$file = fopen('whatevertname.csv', 'w+');
foreach ($data as $value) {
fputcsv($file, $value);
}
fclose($file);
答案 1 :(得分:0)
假设您正在使用fputcsv()函数编写csv文件,
在使用fputcsv()
之前插入第一行数据后,生成的'csv_array'结构应如下所示Array
(
[0] => Array
(
[0] => date
[1] => A
[2] => B
[3] => C
[4] => D
[5] => E
[6] => F
[7] => G
[8] => H
[9] => I
[10] => A
[11] => J
[12] => B
)
[1] => Array
(
[0] => 2014-12-12
[1] => 1
[2] => 2
[3] => 2
[4] => No
[5] => New
[6] => New
[7] => 1
[8] => 1
[9] => 1
[10] => 1
[11] => 1
[12] => 1
)
)