0

我有一个如下的一维数组。(它可以动态延伸到任何长度)

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
    )

)
4

2 回答 2

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;
于 2012-04-28T17:14:35.117 回答
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>';
?>

你的原始数组应该在变量$array

于 2012-04-28T17:39:41.177 回答