2 回答
TA贡献1900条经验 获得超5个赞
在 JS 中,它被称为对象,但在 PHP 中,您将使用关联数组。在你的例子中,我认为你有一个关联数组的数组。它看起来像这样:
$books = [
[
"membername" => "NAME",
"bookingdate" => "2020-02-03",
"categoryid" => 1,
"dailyworkhourssum" => "7.70"
],
[
"membername" => "NAME",
"bookingdate" => "2020-02-03",
"categoryid" => 3,
"dailyworkhourssum" => "1.2"
],
[
"membername" => "NAME",
"bookingdate" => "2020-02-05",
"categoryid" => 3,
"dailyworkhourssum" => "7.70"
]
];
如果您想合并具有相同“bookingdate”的数组,那么我建议您循环遍历该数组,并将其元素添加到另一个以 bookingdates 作为键的关联数组,并检查是否已经存在这样的键,然后合并数组, 像这样:
$merged = [];
foreach ($books as $book) {
$date = $book['bookingdate'];
if (isset($merged[$date])) {
$merged[$date] = $merged[$date] + $book;
} else {
$merged[$date] = $book;
}
}
我认为这不是一个有效的代码(没有时间,抱歉),但我希望您能明白这个想法。
如果您想要一个“列表”而不是关联数组,那么您可以这样做:
$mergedList = array_values($merged);
这样你就可以摆脱字符串键了。
TA贡献1804条经验 获得超2个赞
如果我理解正确的话,您将获得一个包含 4 列和可变行数的表,并且您希望将其转换为具有可变列数的表。为此,使用每一项都与前一项不同的数据结构可能会使一切变得比它需要的更困难。我建议你使用固定结构:
// I'm assuming you have a PHP array as starting point
$input = [
[
'membername' => 'NAME',
'bookingdate' => '2020-02-03',
'categoryid' => 1,
'dailyworkhourssum' => '7.70',
],
[
'membername' => 'NAME',
'bookingdate' => '2020-02-03',
'categoryid' => 3,
'dailyworkhourssum' => '1.2',
],
[
'membername' => 'NAME',
'bookingdate' => '2020-02-05',
'categoryid' => 3,
'dailyworkhourssum' => '7.70',
],
];
$output = [];
foreach ($input as $data) {
// We'll group by booking date
if (!isset($output[$data['bookingdate']])) {
$output[$data['bookingdate']] = [
'membername' => $data['membername'],
'bookingdate' => $data['bookingdate'],
'categoryid' => $data['categoryid'],
'dailyworkhourssum' => [],
];
}
// A single date may have several daily work hours
$output[$data['bookingdate']]['dailyworkhourssum'][] = $data['dailyworkhourssum'];
}
// We discard array keys (we only needed them to group)
echo json_encode(array_values($output));
[{
"membername": "NAME",
"bookingdate": "2020-02-03",
"categoryid": 1,
"dailyworkhourssum": ["7.70", "1.2"]
}, {
"membername": "NAME",
"bookingdate": "2020-02-05",
"categoryid": 3,
"dailyworkhourssum": ["7.70"]
}]
无论您在何处使用此 JSON,您只需要循环该dailyworkhourssum数组即可。您可能还想在打印表格之前循环整个结构并保留一个计数器以确定最大列数,以便您可以在需要的地方绘制空单元格(表格是矩形的)。
- 2 回答
- 0 关注
- 93 浏览
添加回答
举报