我正在从API接收具有可变字段数的数组,并试图将其放入表中。
示例对象如下所示:
array
'silver' =>
array
'assets' =>
array
'Article' => float 2
'ROS_Medium_1' => float 37704
'ROS_Medium_2' => float 37711
'ROS_Medium_3' => float 37546
'ROS_Leaderboard_Footer' => float 37941
'ROS_Leaderboard_Infinite Scroll' => float 3636
'price' => float 375
'discount' => int 0
'banner_cpm' => float 12.79
'banner_sov' => float 0.0099
'content_cpm' => float 150
'content_sov' => float 0.0028
'fixed_cpm' => float 0
'blended_cpm' => float 26.26
'gold' =>
array
'assets' =>
array
'Article' => float 2
'ROS_Leaderboard' => float 15212
'ROS_CCF' => float 1
'ROS_Halfpage' => float 15212
'ROS_Medium_1' => float 12459
'ROS_Medium_2' => float 12476
'ROS_Medium_3' => float 12476
'ROS_Leaderboard_Footer' => float 12390
'ROS_Leaderboard_Infinite Scroll' => float 1239
'price' => int 500
'discount' => int 0
'banner_cpm' => float 18.84
'banner_sov' => float 0.008
'content_cpm' => float 150
'content_sov' => float 0.0028
'fixed_cpm' => float 0
'blended_cpm' => float 29.8
列的数量等于顶级阵列的数量(这里是银和金)
顶级数组的数量可能会有所不同,资产子数组也可能因数组而异(请注意示例代码中的"黄金"数组有更多资产)。数组中的每个资产和每个其他键都应该有一行。
将所有这些信息转换为表格格式的最干净的方法是什么?据我所知,第一步是制作一个所有独特资产的数组。但是,如果没有笨拙地嵌套一堆前臂环,我不知道该从这里走到哪里。
所需的输出看起来像http://i.imgur.com/m0IJpUj.png
你可以用多种方式来做这件事,我会这样做:
样本值:
$values_from_api = array(
'silver' => array(
'assets' => array(
'Article' => 2.0,
'ROS_Medium_1' => 37704.0,
'ROS_Medium_2' => 37711.0,
'ROS_Medium_3' => 37546.0,
'ROS_Leaderboard_Footer' => 37941.0,
'ROS_Leaderboard_Infinite Scroll' => 3636.0,
'price' => 375,
'discount' => 0,
'banner_cpm' => 12.79,
'banner_sov' => 0.0099,
'content_cpm' => 150.0,
'content_sov' => 0.0028,
'fixed_cpm' => 0.0,
'blended_cpm' => 26.26,
),
),
'gold' => array(
'assets' => array(
'Article' => 2.0,
'ROS_Leaderboard' => 15212.0,
'ROS_CCF' => 1.0,
'ROS_Halfpage' => 15212.0,
'ROS_Medium_1' => 12459.0,
'ROS_Medium_2' => 12476.0,
'ROS_Medium_3' => 12476.0,
'ROS_Leaderboard_Footer' => 12390.0,
'ROS_Leaderboard_Infinite Scroll' => 1239.0,
'price' => 500,
'discount' => 0,
'banner_cpm' => 18.84,
'banner_sov' => 0.008,
'content_cpm' => 150.0,
'content_sov' => 0.0028,
'fixed_cpm' => 0.0,
'blended_cpm' => 29.8,
),
),
);
首先,你应该去掉所有必要的列:
$left_columns = array();
foreach($values_from_api as $type_key => $type) {
foreach($type['assets'] as $columns => $value) {
$left_columns[] = $columns;
}
}
$left_columns = array_unique($left_columns);
在你收集了必要的列之后,你可以像这样打印它们:
<table border="1" cellpadding="10">
<thead>
<th width="200"></th>
<th>Silver</th>
<th>Gold</th>
</thead>
<tbody>
<?php foreach($left_columns as $key => $column_name): ?>
<tr>
<td><?php echo $column_name; ?></td>
<?php
foreach($values_from_api as $type_key => $type) {
foreach($type as $columns => $value) {
if(isset($value[$column_name])) {
echo "<td>$value[$column_name]</td>";
} else {
echo "<td>N/A</td>";
}
}
}
?>
</tr>
<?php endforeach; ?>
</tbody>
</table>