我尝试将数组对象映射到表中。实际上,我的代码正在运行,但执行起来可能很重(使用3 foreach ),这可以缩短或改进吗?
我的数据(存储在 $ data 中)
Array
(
[0] => stdClass Object
(
[code] => jne
[name] => Jalur Nugraha Ekakurir (JNE)
[costs] => Array
(
[0] => stdClass Object
(
[service] => CTC
[description] => JNE City Courier
[cost] => Array
(
[0] => stdClass Object
(
[value] => 17000
[etd] => 2-3
[note] =>
)
)
)
[1] => stdClass Object
(
[service] => CTCOKE
[description] => JNE City Courier
[cost] => Array
(
[0] => stdClass Object
(
[value] => 15000
[etd] => 3-4
[note] =>
)
)
)
)
)
[1] => stdClass Object
(
[code] => J&T
[name] => J&T Express
[costs] => Array
(
[0] => stdClass Object
(
[service] => EZ
[description] => Regular Service
[cost] => Array
(
[0] => stdClass Object
(
[value] => 20000
[etd] =>
[note] =>
)
)
)
)
)
)
我的代码
foreach ($data as $data) {
$h = '<tr><th colspan="3">'.$data->{'name'}.'</th></tr>';
$s = "";
foreach ($data->{'costs'} as $subdata) {
foreach ($subdata->{'cost'} as $ev) {
$s .= '<tr><td>'.$subdata->{'service'}.' <small class="text-muted"><em>'.$subdata->{'description'}.'</em></small></td><td style="width:100px;" class="text-center">'.$ev->{'etd'}.' Days</td><td style="width:120px;"><span class="pull-left">Rp.</span><span class="pull-right">'.$ev->{'value'}.'</span></td></tr>';
}
}
$buildHTML .= $h.$s;
}
echo '<table class="table table-bordered table-hover"><tbody>'.$buildHTML.'</tbody></table>';
感谢您的帮助,抱歉我的英语不好。