我需要在第二级合并两个不同键名但数量相同的数组。
我想要的输出是数组3。
我尝试了很多变化来实现这一目标。
我最好的尝试类似于以下内容,但它破坏了我的关键名称:
$results = array();
foreach($arr1 as $key => $array)
{
foreach($array as $user => $value)
{
$results[$user]['name'] = $value;
}
}
foreach($arr2 as $key => $array)
{
foreach($array as $user => $value)
{
$results[$user]['name2'] = $value;
}
}
数组1:
Array
(
[usera] => Array
(
[0] => Array
(
[user] => usera
[duration_s] => 15
)
[1] => Array
(
[user] => usera
[duration_s] => 9
)
)
[userb] => Array
(
[2] => Array
(
[user] => userb
[duration_s] => 21
)
[3] => Array
(
[user] => userb
[duration_s] => 19
)
)
)
数组2:
Array
(
[102] => Array
(
[0] => Array
(
[user] => 102
[duration_s2] => 54
)
[1] => Array
(
[user] => 102
[duration_s2] => 378
)
)
[103] => Array
(
[2] => Array
(
[usernr] => 103
[duration_s2] => 299
)
[3] => Array
(
[usernr] => 103
[duration_s2] => 110
)
)
)
数组3:
Array
(
[usera] => Array
(
[0] => Array
(
[user] => usera
[duration_s] => 15
[usernr] => 102
[duration_s2] => 54
)
[1] => Array
(
[user] => usera
[duration_s] => 9
[usernr] => 102
[duration_s2] => 378
)
)
[userb] => Array
(
[2] => Array
(
[user] => userb
[duration_s] => 21
[usernr] => 103
[duration_s2] => 299
)
[3] => Array
(
[user] => userb
[duration_s] => 19
[usernr => 103
[duration_s2] => 110
)
)
)
答案 0 :(得分:0)
使用array_values()
尝试以下代码:
<?php
$array1 = [
'usera' => [
0=> ['user' => 'usera','duration_s' => 15],
1=> ['user' => 'usera','duration_s' => 9],
],
'userb' => [
2=> ['user' => 'usera','duration_s' => 15],
3=> ['user' => 'usera','duration_s' => 9],
],
];
$array2 = [
102 => [
0=> ['usernr' => 102,'duration_s2' => 54],
1=> ['usernr' => 102,'duration_s2' => 378]
],
103 => [
2=> ['usernr' => 103,'duration_s2' => 299],
3=> ['usernr' => 103,'duration_s2' => 110]
],
];
$array2 = array_values($array2);
$array1 = array_values($array1);
foreach($array1 as $index=>$ar1){
foreach ($ar1 as $index2=>$ar2){
$array1[$index][$index2] = array_merge($ar2,$array2[$index][$index2]);
}
}
print_r($array1);
答案 1 :(得分:0)
要合并阵列,您还可以执行以下操作:
$index = 0;
foreach ($arr2 as $key => $value) { // changing the indexing of second array
$arr3[$index] = $value;
$index++;
}
$results = array();
$count = 0;
foreach ($arr1 as $index => $value) { // merging two array
$total = 0;
foreach ($value as $key => $val) {
$merge_value = array_merge($val,$arr3[$count][$total]);
$results[$index][$total] = $merge_value;
$total++;
}
$count++;
}
print_r($results);
在此结果中,您的索引不会丢失。