-2

I am writing a PHP plugin, which builds a multidimensional array, in the format below, so that it can be passed back to the template system and parsed as tags.

I am fetching the information from a database:

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

This is the array structure required:

   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)
        )
)

Could someone point me in the right direction, so that from the returned data, it splits the events into the appropriate keys (alphabetical key), sored alpha by the event_name.

The end result is to have this

A - Ambulance Training - Apple Bobbing B - Badminton - Bowling

BigDistance
  • 135
  • 1
  • 12

3 Answers3

2

try this, it is tested

$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++;
}

OR THIS

$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);
Deepak Mallah
  • 2,786
  • 4
  • 17
  • 26
0

I'd do something like this:

$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);
}
giorgio
  • 9,517
  • 2
  • 25
  • 40
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'],
    );
}
bbldzr
  • 151
  • 8