Page 1 of 1

[SOLVED] Array Organizing

Posted: Wed Sep 01, 2010 2:14 am
by HiddenS3crets
I have been attempting to write a script that takes an array of information and puts it into a new array in an organized manner like this:

Code: Select all

Array
(
        [category1] => Array 
                             (
                                 [0] => Array
                                           (
                                                   [message] => Hi there
                                                   [time] => 10:55
                                            )
                                 [1] => Array
                                           (
                                                   [message] => Running
                                                   [time] => 5:32
                                            )
                             ) 
        [category2] => Array 
                             (
                                 [0] => Array
                                           (
                                                   [message] => Yo
                                                   [time] => 8:25
                                            )
                             ) 
)
The main array is broken down into categories and each category holds an array of messages.

My thought process is that the main array is declared initially and as I loop through messages I add new categories to the array if they do not exist (via array_key_exists())
Then I can add the message to the category. If I come across a message whose category already exists in the array then the message is simply added to that category as the next key.

My current code looks like this:

Code: Select all

  $notes = array();
  foreach(...)
  {
      $current_note = array();
      $current_note['message_id'] = "$msg->id";
      $current_note['message'] = "$message";
     
      // create new category if it doesn't exist
      if(!array_key_exists($category, $notes))
      {
        $new_category_array = array("$category" => array());
        array_merge($notes, $new_category_array);
      }
        
      array_push($notes[$category], $current_note);
  }
What would be the best way to go about creating and adding to the array? I have been trying to figure this out for a good amount of time now...

Re: Array Organizing

Posted: Wed Sep 01, 2010 2:41 am
by HiddenS3crets
Wow the whole time the issue with my script was that I was doing

Code: Select all

array_merge($new_category_array, $notes)
instead of

Code: Select all

$notes = array_merge($new_category_array, $notes)