views:

148

answers:

1

I would like to make this multidimensional array more readable by using one of its sub key values as index. So this array:

array(
[0]=>array('group_id'=>'2','group_name'=>'red','members'=>array()),
[1]=>array('group_id'=>'3','group_name'=>'green','members'=>array()),
[2]=>array('group_id'=>'4','group_name'=>'blue','members'=>array()), 
);

should become this:

array(
[2]=>array('group_name'=>'red','members'=>array()),
[3]=>array('group_name'=>'green','members'=>array()),
[4]=>array('group_name'=>'blue','members'=>array()), 
);

Sure i could loop through and rebuild the array, but i was wondering what would be an expert take at this ?

+1  A: 

I would create an index that uses references to point to rows in the original array. Try something like this:

$group_index = array();
foreach($foo as &$v){
  $g = $v['group_id'];
  if(!array_key_exists($g, $group_index)){
    $group_index[$g] = array();
  }
  $group_index[$g][] = $v;
}

echo print_r($group_index[2], true);

# Array
# (
#     [0] => Array
#         (
#             [group_id] => 2
#             [group_name] => red
#             [members] => Array
#                 (
#                 )
# 
#         )
# 
# )

Note: The index will always return an array. If you have multiple items with the same group_id, they will all be rolled into the result.

macek
Thank you. I initially sort of hoped i could avoid a loop, but in any case, it turns out i need to loop once through my initial array for other reasons, so i'll accept your answer as it does the job!
pixeline
pixeline, np. You could do all the index/indices building in the loop that builds this array :D
macek