美好的一天!我在合并/组合/连接数组时遇到错误。
例如我有数组,
$array1 [] = array(
'var1' => $var1,
'var2' => $var2,
'var3' => $var3,
);
$array2 [] = array(
'var4' => $var4,
'var5' => $var5,
'var6' => $var6,
);
这些数组内部有多条记录,但记录数相同。 当我var_dump它们时,结构看起来像这样:
//array1
array(3){
[0]=>array(3){
["var1"]=> string (4) "var1"
["var2"]=> string (4) "var2"
["var3"]=> string (4) "var3"
}
[1]=>array(3){
["var1"]=> string (4) "var1"
["var2"]=> string (4) "var2"
["var3"]=> string (4) "var3"
}
[2]=>array(3){
["var1"]=> string (4) "var1"
["var2"]=> string (4) "var2"
["var3"]=> string (4) "var3"
}
}
//array2
array(3){
[0]=>array(3){
["var4"]=> string (4) "var4"
["var5"]=> string (4) "var5"
["var6"]=> string (4) "var6"
}
[1]=>array(3){
["var4"]=> string (4) "var4"
["var5"]=> string (4) "var5"
["var6"]=> string (4) "var6"
}
[2]=>array(3){
["var4"]=> string (4) "var4"
["var5"]=> string (4) "var5"
["var6"]=> string (4) "var6"
}
}
我想添加两个数组
$array_combined [] = array(
'var1' => $var1,
'var2' => $var2,
'var3' => $var3,
'var4' => $var4,
'var5' => $var5,
'var6' => $var6,
);
我认为当var_dump(ed):
时,结构应如下所示//array_combined
array(3){
[0]=>array(6){
["var1"]=> string (4) "var1"
["var2"]=> string (4) "var2"
["var3"]=> string (4) "var3"
["var4"]=> string (4) "var4"
["var5"]=> string (4) "var5"
["var6"]=> string (4) "var6"
}
[1]=>array(3){
["var1"]=> string (4) "var1"
["var2"]=> string (4) "var2"
["var3"]=> string (4) "var3"
["var4"]=> string (4) "var4"
["var5"]=> string (4) "var5"
["var6"]=> string (4) "var6"
}
[2]=>array(3){
["var1"]=> string (4) "var1"
["var2"]=> string (4) "var2"
["var3"]=> string (4) "var3"
["var4"]=> string (4) "var4"
["var5"]=> string (4) "var5"
["var6"]=> string (4) "var6"
}
}
我试过了:
$array_combine = array_combine($array1, $array2);
$array_merge = array_merge($array1, $array2);
$array_merge_recursive = array_merge_recursive($array1, $array2);
但我一直收到这个错误:
注意:未定义索引:C ++在D:\ xampp \ htdocs \ vra \ GetVM - Copy.php第365行
我在那里发布的代码与我的真实代码相似
365行包含echo($ record ['var4'])
我正在做这样的事情来输出合并/合并数组。
$array_merge = merge_array($array1, $array2)
foreach ( $array_merge as $record ) {
echo ( $record['var1'] );
echo ( $record['var2'] );
echo ( $record['var3'] );
echo ( $record['var4'] );//this is were the error occurs
echo ( $record['var5'] );//same error here
echo ( $record['var6'] );//same error here
}
尝试使用array_combine(),array_merge_recursive和$ combined_array = $ array1 + $ array2
答案 0 :(得分:0)
我想这个问题源于您使用多维数组并尝试将它们组合为单维数组。
而不是
$array_merge = array_merge($array1, $array2);
尝试
$array_merge[0] = array_merge($array1[0], $array2[0]);
$array_merge[1] = array_merge($array1[1], $array2[1]);
$array_merge[2] = array_merge($array1[2], $array2[2]);
[ ... ]
如果您想要严格地将它们组合在一起,而不是从第一个与第二个值重叠,请使用
$array_merge = $array1 + $array2;
有关阵列合并的其他说明,请参阅php.net