[SOLVED] Array Organizing
Posted: Wed Sep 01, 2010 2:14 am
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:
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:
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...
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
)
)
)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);
}