2012-04-28 74 views
0

我有一個一維數組,如下所示。 (它可以動態地擴展到任何長度)如何將一個數組拆分爲3個數組

Array 
(
[0] => Array 
    (
     [city] => Trivandrum 
     [citykey] => ab5416c6 
    ) 

[1] => Array 
    (
     [city] => Kochi 
     [citykey] => 85cb7d9c 
    ) 

[2] => Array 
    (
     [city] => Alappuzha 
     [citykey] => 4d5f200e 
    ) 

[3] => Array 
    (
     [city] => Mumbai 
     [citykey] => 47d98024 
    ) 

) 

現在我想將它分成3個數組。我的意思是我想將一個數組分割成3個數組,如下所示。

Array 
(
[0] => Array 
    (
     [city] => Trivandrum 
     [citykey] => ab5416c6 
    ) 
[1] => Array 
    (
     [city] => Mumbai 
     [citykey] => 47d98024 
    ) 

) 

Array 
(
[0] => Array 
    (
     [city] => Kochi 
     [citykey] => 85cb7d9c 
    ) 

) 

Array 
(
[0] => Array 
    (
     [city] => Alappuzha 
     [citykey] => 4d5f200e 
    ) 

) 
+2

取決於你如何想它分爲3個不同的陣列,[array_chunk( )](http://www.php.net/manual/en/function.array-chunk.php)可能會有所幫助。 – drew010 2012-04-28 17:14:30

+0

你想要每個數組包含什麼?這個問題並不清楚。你能否提供這個四元素數組的預期輸出? – 2012-04-28 17:15:14

+0

我想得到這個輸出。陣列 ( [0] =>數組 ( [城市] =>特里凡德琅 [citykey] => ab5416c6 ) [1] =>數組 ( [城市] =>孟買 [citykey] => 47d98024 ) ) 陣列 ( [0] =>數組 ( [城市] =>高知 [citykey] => 85cb7d9c ) ) 陣列 ( [0] =>陣列 ( [城市] =>阿拉普扎 [citykey] => 4d5f200e ) ) – Sunil 2012-04-28 17:19:16

回答

1
$a = range(1,4); // example input array of 4 items 
$n = 3; // number of pieces you want in the output array $b 

$b = array_fill(0, $n, array()); 
for($i=0; $i<count($a); $i++) { 
    $b[$i % $n][] = $a[$i]; 
} 

print_r($b); 

// if you need to split them out 
list($a1,$a2,$a3) = $b; 
0

試試這個代碼:

<? 
$i=0; 
$array=Array(0=> Array("city" => 'Trivandrum', 
     "citykey" => 'ab5416c6' 
    ), 
1 => Array 
    (
     "city" => 'Kochi', 
     "citykey" => '85cb7d9c' 
    ), 
2 => Array 
    (
     "city" => 'Alappuzha', 
     "citykey" => '4d5f200e' 
    ), 
3 => Array 
    (
     "city" => 'Mumbai', 
     "citykey" => '47d98024' 
    ) 
); 
$array_0=array(); 
$array_1=array(); 
$array_2=array(); 
foreach ($array as $value) 
    { 
    $name='array_'.$i%3; 
    $temp[0]=$value; 
    $$name=array_merge_recursive($$name, $temp); 
    $i++; 
    } 
echo '<pre>'; 
print_r($array_0); 
print_r($array_1); 
print_r($array_2); 
echo '</pre>'; 
?> 

你原來的數組應該是變量$陣列

+0

我沒有看到你在代碼中聲明'$ array'或'$ i'的地方。 – 2012-04-28 17:40:24

相關問題