简体   繁体   中英

php multi-dimensional array manipulation: replace index by one of its values

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM