在尝试操作具有相似性的两个数组时遇到了麻烦。
第一个数组具有以下结构:
array(3) {
[0]=>
array(2) {
["id_modulo"]=>
string(3) "114"
["nome_modulo"]=>
string(16) "1. Acessos"
}
[1]=>
array(2) {
["id_modulo"]=>
string(3) "118"
["nome_modulo"]=>
string(27) "4. Área de Vivência"
}
[2]=>
array(2) {
["id_modulo"]=>
string(3) "128"
["nome_modulo"]=>
string(20) "14. Supressão"
}
}
第二个结构:
array(6) {
[0]=>
array(4) {
["id_modulo"]=>
string(3) "114"
["id_pergunta"]=>
string(3) "547"
["pergunta"]=>
string(58) "Example"
["resposta"]=>
string(1) "C"
}
[1]=>
array(4) {
["id_modulo"]=>
string(3) "114"
["id_pergunta"]=>
string(3) "548"
["pergunta"]=>
string(57) "Example"
["resposta"]=>
string(1) "C"
}
[2]=>
array(4) {
["id_modulo"]=>
string(3) "118"
["id_pergunta"]=>
string(3) "549"
["pergunta"]=>
string(76) "Example"
["resposta"]=>
string(1) "C"
}
[3]=>
array(4) {
["id_modulo"]=>
string(3) "114"
["id_pergunta"]=>
string(3) "550"
["pergunta"]=>
string(43) "Example"
["resposta"]=>
string(1) "C"
}
}
我想要做的是将第二个数组追加到第一个数组中,其中id_modulo
是相同的。基本上,第一个数组包含一些模块详细信息,第二个数组包含每个模块的问题和答案。
因此,第二个数组中与id_module
节点相对应的所有问题都必须插入第一个数组中。
我已经使用array_merge
尝试了很多示例,并使用array_push
进行了循环,也遵循了tutorial,但是无法实现我期望的最终结果。
编辑
输出示例:
[0]=>
array(2) {
["id_modulo"]=>
string(3) "114"
["nome_modulo"]=>
string(16) "1. Acessos"
["items"]=>
[0]=>
array(4) {
["id_modulo"]=>
string(3) "114"
["id_pergunta"]=>
string(3) "547"
["pergunta"]=>
string(58) "Example"
["resposta"]=>
string(1) "C"
}
[1]=>
array(4) {
["id_modulo"]=>
string(3) "114"
["id_pergunta"]=>
string(3) "548"
["pergunta"]=>
string(57) "Example"
["resposta"]=>
string(1) "C"
}
}
答案 0 :(得分:2)
首先创建一个临时数组,以存储第一个数组中给定id_modulo
的索引。因此,在将item
从第二个数组推送到第一个数组时,我们不必每次都进行搜索。
$arrModuleIndex = [];
// $arr here is your first array.
foreach($arr as $key => $data){
$arrModuleIndex[$data['id_modulo']] = $key;
}
Output:
Array
(
[114] => 0
[118] => 1
[128] => 2
)
现在循环遍历第二个数组,并根据临时数组在索引处将其推到第一个数组的items
。
// Here $arr2 is your second array
foreach($arr2 as $data){
$arr[$arrModuleIndex[$data['id_modulo']]]['items'][] = $data;
}
Output:
Array
(
[0] => Array
(
[id_modulo] => 114
[nome_modulo] => 1. Acessos
[items] => Array
(
[0] => Array
(
[id_modulo] => 114
[id_pergunta] => 547
[pergunta] => Example
[resposta] => C
)
[1] => Array
(
[id_modulo] => 114
[id_pergunta] => 548
[pergunta] => Example
[resposta] => C
)
[2] => Array
(
[id_modulo] => 114
[id_pergunta] => 550
[pergunta] => Example
[resposta] => C
)
)
)
[1] => Array
(
[id_modulo] => 118
[nome_modulo] => 4. Área de Vivência
[items] => Array
(
[0] => Array
(
[id_modulo] => 118
[id_pergunta] => 549
[pergunta] => Example
[resposta] => C
)
)
)
[2] => Array
(
[id_modulo] => 128
[nome_modulo] => 14. Supressão
)
)