我想要以不同的方式合并两个数组。假设我有以下数组:
$q_id = array(0 => 7, 1 => 8, 2 => 9)
$a_id = array(
0 => 24,
1 => 25,
2 => 26,
3 => 27,
4 => 28,
5 => 29,
6 => 30,
7 => 31,
8 => 32,
9 => 33,
10 => 34,
11 => 35,
)
我的目标是:
array(
[7] => array
(
[0] => 24
[1] => 25
[2] => 26
[3] => 27
)
[8] => array
(
[4] => 28
[5] => 29
[6] => 30
[7] => 31
)
[9] => array
(
[8] => 32
[9] => 33
[10] => 34
[11] => 35
)
)
数组操作的内置函数不符合我的需要。从stackoverflow上的帖子中获取的递归合并代码:Combine arrays to form multidimensional array in php创建一个数组,其中作为子数组执行的三个键中的每一个只接收每组四个中的第一个值:
array(
[7] => array
(
[0] => 24
)
[8] => array
(
[4] => 28
)
[9] => array
(
[8] => 32
)
我很肯定解决方案在于递归(可能修改了上面链接中提供的代码片段),但我只是不知道该怎么做。
非常感谢帮助。
答案 0 :(得分:0)
这应该适合你:
(这里我只是array_combine()
$q_id
数组作为键,$a_id
数组作为值。我在其中使用大小为count($a_id)/count($q_id)
的X块{{3} }对于值数组)
<?php
$q_id = [7, 8, 9];
$a_id = [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,];
$result = array_combine($q_id, array_chunk($a_id, count($a_id)/count($q_id), TRUE));
print_r($result);
?>
输出:
Array
(
[7] => Array
(
[0] => 24
[1] => 25
[2] => 26
[3] => 27
)
[8] => Array
(
[4] => 28
[5] => 29
[6] => 30
[7] => 31
)
[9] => Array
(
[8] => 32
[9] => 33
[10] => 34
[11] => 35
)
)