问题
how to join two multidimensional arrays in php? I have two multidimensional arrays A and B. I need to join A and B to form a new array C as follows
$A = array(
array("a1"=>1,"b1"=>2,"c1"=>"A"),
array("a1"=>1,"b1"=>16,"c1"=>"Z"),
array("a1"=>3,"b1"=>8,"c1"=>"A"));
$B = array(
array("a2"=>1,"b2"=>2,"b2"=>"A"),
array("a2"=>1,"b2"=>16,"b2"=>"G"),
array("a2"=>3,"b2"=>8,"b2"=>"A"));
//join A and B to form C
$C=array(
array("a1"=>1,"b1"=>2,"c1"=>"A"),
array("a1"=>1,"b1"=>16,"c1"=>"Z"),
array("a1"=>3,"b1"=>8,"c1"=>"A"),
array("a2"=>1,"b2"=>2,"b2"=>"A"),
array("a2"=>1,"b2"=>16,"b2"=>"G"),
array("a2"=>3,"b2"=>8,"b2"=>"A"));
回答1:
Use the array_merge function, like this:
$C = array_merge($A, $B);
print_r($C);
When I run the above script it'll output:
Array (
[0] => Array (
[a1] => 1
[b1] => 2
[c1] => A
)
[1] => Array (
[a1] => 1
[b1] => 16
[c1] => Z )
[2] => Array (
[a1] => 3
[b1] => 8
[c1] => A
)
[3] => Array (
[a2] => 1
[b2] => A
)
[4] => Array (
[a2] => 1
[b2] => G
)
[5] => Array (
[a2] => 3
[b2] => A
)
)
Take a quick read here: http://php.net/manual/function.array-merge.php
回答2:
$C = array_merge($A, $B);
should do the trick (docs).
回答3:
Did you try some PHP array functions? I think some of these work: array_merge_recursive(), array_merge().
$array1 = array("farbe" => "rot", 2, 4);
$array2 = array("a", "b", "farbe" => "grün", "form" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
回答4:
you can also do this as
foreach($B as $key => $value){
$C[$key] = array_merge($A[$key], $B[$key]);
}
回答5:
Hi I have faced same situation where i had to show duplicate events in calendar
So i used this solution:-
public function array_interlace() {
$args = func_get_args();
$total = count($args);
if($total < 2) {
return FALSE;
}
$i = 0;
$j = 0;
$arr = array();
foreach($args as $arg) {
foreach($arg as $v) {
$arr[$j] = $v;
$j += $total;
}
$i++;
$j = $i;
}
ksort($arr);
return array_values($arr);
}
Required output of array
$a = array('a', 'b', 'c', 'd');
$b = array('a','e', 'f', 'g');
$c = array('h', 'i', 'j');
$d = array('k', 'l', 'm', 'n', 'o');
print_r(array_interlace($a, $b, $c, $d));
Array
(
[0] => a
[1] => a
[2] => h
[3] => k
[4] => b
[5] => e
[6] => i
[7] => l
[8] => c
[9] => f
[10] => j
[11] => m
[12] => d
[13] => g
[14] => n
[15] => o
)
I found this solution suitable..
来源:https://stackoverflow.com/questions/19109815/how-to-join-two-multidimensional-arrays-in-php