-2

我正在编写一个 PHP 插件,它构建了一个多维数组,格式如下,以便可以将其传递回模板系统并解析为标签。

我正在从数据库中获取信息:

$SQL = SELECT `id`, `name`, `description` FROM (`events`) WHERE `event_category_id` = '1' AND `active` = 1 ORDER BY `name` asc

这是所需的数组结构:

   Array ( 
[A] => Array ( 
    [0] => Array(
        [event_id] => 1
        [event_name] => A - this event name starts with the letter A 
        [event_description] => Example Description) 
    [1] => Array(
        [event_id] => 6
        [event_name] => AB - this event ALSO starts with the letter A 
        [event_description] => Example Description)
        ) 
[B] => Array ( 
    [0] => Array(
        [event_id] => 3
        [event_name] => BA - Event name starts with letter B
        [event_description] => Example Description) 
    [1] => Array(
        [event_id] => 5
        [event_name] => BB - Event name starts with letter B
        [event_description] => Example Description)
        )
)

有人可以指出我正确的方向,以便从返回的数据中,将事件拆分为适当的键(字母键),按 event_name 排序 alpha。

最终的结果是拥有这个

A - 救护车训练 - Apple Bobbing B - 羽毛球 - 保龄球

4

3 回答 3

2

试试这个,它已经过测试

$my_record = array();
$i = 0;
foreach($row as $record){
    $str = $record['name'];
    $ind = strtoupper(str[0]);

    $my_record[$ind][$i]['event_id'] = $record['id'];
    $my_record[$ind][$i]['event_name'] = $record['name'];
    $my_record[$ind][$i]['event_description'] = $record['description'];
    $i++;
}

或这个

$my_record = array();
foreach($row as $record){
    $str = $record['name'];
    $ind = strtoupper(str[0]);

    $my_record[$ind][] = array('event_id'=>$record['id'],'event_name'=>$record['name'],'event_description'=>$record['description']);
}

//check the new array by this 
echo "<pre>"; print_r($my_record);
于 2013-06-28T11:50:12.207 回答
0

我会做这样的事情:

$my_result_array = array();

$result = mysql_query($my_query);
while(list($id, $name, $description) = mysql_fetch_array($result)) {
    $first_letter = strtoupper(substr($name, 0, 1));
    $my_result_array[$first_letter][] = array('id' => $id, 'name' => $name, 'description' => $description);
}
于 2013-06-28T11:50:58.860 回答
0
$array = array()
foreach ($DBResults as $value) {
    $key = strtoupper(substr($value['name'],0,1));
    if (!array_key_exists($key,$array)) {
        $array[$key] = array();
    }
    $array[$key][] = array(
        'event_id' => $value['id'],
        'event_name' => $value['name'],
        'event_description' => $value['description'],
    );
}
于 2013-06-28T11:58:48.190 回答