我今晚努力工作以弄清楚如何将我的数组拆分成很多数组,由数组中的值定义
我可以拥有这个值
$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 )
希望你们理解我的问题,并希望有人能够弄明白。
事先,谢谢。
答案 0 :(得分:6)
array_fill()
可以在这里提供帮助:
$result = array();
foreach ($array as $sub) {
$result[] = array_fill(0, $sub[1], $sub[0]);
}
print_r($result);
在此处查看:[{3}}
答案 1 :(得分:1)
如果我理解正确的目的是创建一个包含10个“苹果”的数组,另一个包含5个“球”
$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);
输出:
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
)
)