0

今晚我一直在努力弄清楚如何将我的数组拆分成很多数组,这些数组由数组中的一个值定义

我可以拥有这个价值

$array = array ( 
    array ("Apple", 10),
    array("Ball", 5) 
);

然后我希望 Apple 有 10 个值为“Apple”的数组,而 Ball 有 5 个值为“Ball”的数组

然后我想出了这个,但输出看起来很奇怪..

$newarray = array();
foreach($array as $val):
    for($i = 1; $i <= $val[1]; $i++):
        $newarray[$i] = $val[0];
    endfor;
endforeach;

print_r($newarray);
// Array ( [0] => Ball [1] => Ball [2] => Ball [3] => Ball [4] => Ball [5] => Ball [6] => Apple [7] => Apple [8] => Apple [9] => Apple [10] => Apple )

希望大家能理解我的问题,希望有人能解答。

提前,谢谢。

4

2 回答 2

6

array_fill()可以在这里提供帮助:

$result = array();

foreach ($array as $sub) {
  $result[] = array_fill(0, $sub[1], $sub[0]);
}

print_r($result);

在此处查看实际操作:http: //viper-7.com/MhnWFt

于 2012-07-11T23:55:14.750 回答
1

If I understood correctly the purpose is to create an array with 10 "Apples" and another one with 5 "Balls"

$array = array ( 
    array ("Apple", 10),
    array("Ball", 5) 
);
$newarray = array();
foreach($array as $key => $val){
    $tmparray = null;
    for($i = 1; $i <= $val[1]; $i++){
        $tmparray[$i] = $val[0];
    }
    $newarray[] = $tmparray;
}
print_r($newarray);

output:

Array
(
    [0] => Array
        (
            [1] => Apple
            [2] => Apple
            [3] => Apple
            [4] => Apple
            [5] => Apple
            [6] => Apple
            [7] => Apple
            [8] => Apple
            [9] => Apple
            [10] => Apple
        )

    [1] => Array
        (
            [1] => Ball
            [2] => Ball
            [3] => Ball
            [4] => Ball
            [5] => Ball
        )

)
于 2012-07-12T00:00:07.367 回答