使用alpha键创建多维数组

时间:2013-06-28 11:43:21

标签: php arrays sorting multidimensional-array expressionengine

我正在编写一个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。

最终结果就是拥有这个

一个   - 救护车训练  - 咬苹果游​​戏 乙   - 羽毛球   - 保龄球

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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);
}

答案 2 :(得分: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'],
    );
}