我有一个这样的数组结构(这是CSV格式化它的方式):
Array(
0 => Array(
0 => person1
1 => person2
2 => person3
//all the way to 9
),
1 => Array(
0 => id belonging to person 1
1 => id belonging to person 2
2 => id belonging to person 3
),
2 => Array(
0 => id belonging to person 1
1 => id belonging to person 2
2 => id belonging to person 3
),
//all the way to 20
)
我正在尝试对一个新的数组(数组)进行排序,每个索引都是与上面0
索引中的键对应的值。 即,person1
指向一个数组,其中包含数组 1-20 外部的所有 id。
在索引0
之后的每个数组中,它包含 20 个 id,0 属于第一个数组中的键 0。
我试图实现的结构如下所示:
Array(
[person1] => Array(
id belonging to person 1
id belonging to person 1
id belonging to person 1
),
[person2] => Array(
id belonging to person 2
id belonging to person 2
id belonging to person 2
),
[person3] => Array(
id belonging to person 3
id belonging to person 3
id belonging to person 3
),
)
到目前为止,我的尝试已经奏效,但是,我不得不对一些索引进行硬编码。 实现所需结构的最佳解决方案是什么?
我有点不确定这是否是你要找的......
<?php
$arr = Array(
0 => Array(
0 => "person1",
1 => "person2",
2 => "person3"
//all the way to 9
),
1 => Array(
0 => "id belonging to person 1",
1 => "id belonging to person 2",
2 => "id belonging to person 3"
),
2 => Array(
0 => "id belonging to person 1",
1 => "id belonging to person 2",
2 => "id belonging to person 3"
)
);
foreach($arr[0] AS $id=>$name)
{
$ids[$id] = $name;
}
foreach(array_slice($arr,1) AS $persons)
{
foreach($persons AS $id=>$person)
{
// make sure to check if $ids[$id] exist and handle it as you like.
// if(isset($ids[$id]))
$people[$ids[$id]][] = $person;
}
}
print_r($people);
?>
结果:
Array
(
[person1] => Array
(
[0] => id belonging to person 1
[1] => id belonging to person 1
)
[person2] => Array
(
[0] => id belonging to person 2
[1] => id belonging to person 2
)
[person3] => Array
(
[0] => id belonging to person 3
[1] => id belonging to person 3
)
)
编辑:应该注意的是,我没有检查该人的ID是否存在于$ids数组中,也没有设置$people。