I’d like to group an array that I’ve returned from a mysql database. I’ve named the array $item_info and I’d like to group it by folder_id.
First, two related questions:
- Is doing a single query to get the data below and creating new array keys always (or most likely) faster than 2 separate queries (one involving the desired
GROUP BYand the other not). - From what I read on SO it seems it is best to keep the MySQL query simple and sort out the data with PHP. Comments on that general philosophy?
here’s what my database gives back:
$item_info=array(
array("id"=>"1", 'folder_id'="1", "img"=>"/images/button_01.gif"),
array("id"=>"2", 'folder_id'="1", "img"=>"/images/button_02.gif"),
array("id"=>"3", 'folder_id'="2", "img"=>"/images/button_03.gif"),
array("id"=>"4", 'folder_id'="2", "img"=>"/images/button_04.gif"),
array("id"=>"5", 'folder_id'="3", "img"=>"/images/button_05.gif"),
array("id"=>"6", 'folder_id'="3", "img"=>"/images/button_06.gif")
);
here’s how i’d like to array:
$item_info=array(
array(
array("id"=>"1", 'folder_id'="1", "img"=>"/images/button_01.gif"),
array("id"=>"2", 'folder_id'="1", "img"=>"/images/button_02.gif")
),
array(
array("id"=>"3", 'folder_id'="2", "img"=>"/images/button_03.gif"),
array("id"=>"4", 'folder_id'="2", "img"=>"/images/button_04.gif")
),
array(
array("id"=>"5", 'folder_id'="3", "img"=>"/images/button_05.gif"),
array("id"=>"6", 'folder_id'="3", "img"=>"/images/button_06.gif")
));
Since you already have the data in RAM, grouping in PHP seems more than reasonable, since it takes not a lot of processing.
You might want to try