2009-12-15 173 views
2

我相信這很容易,但我找不到合適的功能。混合兩個陣列

我有兩個數組,一個用於x值,一個用於y,現在我想將它們合併爲xyxyxy。

例如:

$ X =陣列( 0 => 10, 1 => 20, 2 => 30 );

$ Y =陣列( 0 => 15, 1 => 25, 2 => 35 );

混合會離開:

$ XY =陣列( 0 => 10, 1 => 15, 2 => 20, 3 => 25, 4 => 30, 5 = > 35 );

回答

2

如果你不能依靠跨兩個陣列相匹配的鍵,你可以嘗試像下面

$x = array("XA" => "X 1", "XB" => "X 2", "XC" => "X 3"); 
$y = array("YA" => "Y 1", "YB" => "Y 2", "YC" => "Y 3"); 
$xy = array(); 
foreach($x as $k => $v) { 
    $xy[] = array_shift($x); 
    $xy[] = array_shift($y); 
} 
0

試試這個

$a = array_merge($x, $y); 
asort($a); 
print_r($a); 
+0

x和y不會永遠按照數字順序排列,只是爲了更容易看到'前後' – Mark 2009-12-15 10:56:11

1
$x = array(0=>10, 1=>20, 2=>30); 
$y = array(0=>15, 1=>25, 2=>35); 
$xy = array(); 
for ($i=0; $i<count(x); $i++) { 
    $xy[] += $x[i]; 
    $xy[] += $y[i]; 
}