php multi-dimensional array manipulation: replace index by one of its values
I would like to make this mul开发者_运维技巧tidimensional 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 ?
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.
精彩评论