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