我正在用laravel建立一个应用程序,我有一个问题,我在php中有两个数组:
Array1
(
[0] => 15
[1] => 15
[2] => 16
[3] => 16
[4] => 17
[5] => 17
[6] => 17
[7] => 17
)
Array2
(
[0] => 0
[1] => 1
[2] => 1
[3] => 2
[4] => 0
[5] => 1
[6] => 2
[7] => 3
)
在这种情况下我不能使用array_chunk因为array2的值是dinamic而array1的key如果我把它组合起来必须不一样,所以,我怎么能把它组合成这样:
Array
(
[15] => Array
(
[0] => 0
[1] => 1
)
[16] => Array
(
[0] => 1
[1] => 2
)
[17] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
)
)
答案 0 :(得分:4)
简单foreach
循环:
$arr1 = [15,15,16,16,17,17,17,17];
$arr2 = [0,1,1,2,0,1,2,3];
$result = [];
foreach($arr1 as $k => $v){
$result[$v][] = $arr2[$k];
}
print_r($result);
输出:
Array
(
[15] => Array
(
[0] => 0
[1] => 1
)
[16] => Array
(
[0] => 1
[1] => 2
)
[17] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
)
)
答案 1 :(得分:2)
$array1 =
[
0 => 15,
1 => 15,
2 => 16,
3 => 16,
4 => 17,
5 => 17,
6 => 17,
7 => 17,
];
$array2 =
[
0 => 0,
1 => 1,
2 => 1,
3 => 2,
4 => 0,
5 => 1,
6 => 2,
7 => 3,
];
$arr = array_unique($array1);
print_r($arr);
$newarray = [];
foreach($arr as $ar){
foreach($array1 as $key => $value){
if($ar == $value){
$newarray[$value][] =$array2[$key];
}
}
}
print_r($newarray);