doushantun0614 2011-02-24 10:49
浏览 42
已采纳

PHP:如何创建锯齿状数组结构来表示数据库中的分组记录

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

  • 写回答

2条回答 默认 最新

  • dongzhun4898 2011-02-24 10:56
    关注

    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.

    <?php
    $channels = array();
    foreach($rows as $row) {
        // Create the channel node if it doesn't exist
        if (!isset($channels[$row->channel_key])) {
            $channels[$row->channel_key] = array(
                'key' => $row->channel_key,
                'programme' => array()
            );
        }
    
        $programme = array(
            'title' => $row->title,
            'start' => $row->start,
            'duration' => $row->duration
        );
    
        // Add to the existing channel node.
        $channels[$row->channel_key]['programme'][] = $programme;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?