PHP:如何创建锯齿状数组结构来表示数据库中的分组记录
这似乎是一个简单的挑战,但我正在努力。
我想使用两个数据库表上的联接查询来检索记录,并将它们表示为数组的数组,其中根数组中的每个元素都是父记录,每个嵌套元素代表子记录。
SQL 查询工作正常,它返回一组行,其中 channel_key
列是分组列。
这是我从行填充数组结构的尝试:
$rows = $db->get_results($query);
$key = '';
$programmes = array();
foreach ($rows as $row) {
$programme = array(
'title' => $row->title,
'start' => $row->start,
'duration' => $row->duration
);
$programmes[] = $programme;
if ($key != $row->channel_key) {
$channels[] = array(
'key' => $row->channel_key,
'programme' => $programmes
);
$key = $row->channel_key;
$programmes = array();
}
}
不幸的是,这仅填充根级数组(与父记录相对应的数组)。
请问有什么建议吗?
谢谢, 蒂姆
This seems like a simple challenge, but I'm struggling.
I want to retrieve records using a join query on two database tables and represent them as an array of arrays, whereby each of the elements in the root array is a parent record and each nested element represents a child record.
The SQL query is working fine, and it returns a set of rows in which the channel_key
column is a grouping column.
Here's my attempt at populating the array structure from the rows:
$rows = $db->get_results($query);
$key = '';
$programmes = array();
foreach ($rows as $row) {
$programme = array(
'title' => $row->title,
'start' => $row->start,
'duration' => $row->duration
);
$programmes[] = $programme;
if ($key != $row->channel_key) {
$channels[] = array(
'key' => $row->channel_key,
'programme' => $programmes
);
$key = $row->channel_key;
$programmes = array();
}
}
Unfortunately this only populates the root level arrays (the ones that correspond to the parent records).
Any suggestions please?
Thanks,
Tim
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您将其分配给频道时,$programmes 数组中只有一个节目。
另一种方法是使用channel_key 构建通道数组。
例如
You only have one programme in the $programmes array when you assign it to the channel.
An alternative would be to build the channel array with the channel_key.
e.g.
简单的解决方案即可。
Simple solution can be.