[英]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. 如果您有多个具有相同
group_id
项目,则所有项目都将group_id
到结果中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.