我有2个数组的列表,
[ "4", "4"] - array of product id .
[ "1", "2"] - array of qty.
如果qty_array中的数量为“ 2”,我只想像[“ 4”,“ 4”,“ 4”]一样合并array_product,如果数量为3,我想像[“ 4” ,“ 4”,“ 4”,“ 4”] 友善的帮助
答案 0 :(得分:1)
使用array_fill(),然后将它们合并。这假定$qty
和$products
的长度都相同。
<?php
$products = [ "4", "5", "8"];
$qty = ["1", "3", "4"];
$result = [];
foreach ($products as $key => $product) {
$result = array_merge(array_fill(0, $qty[$key], $product), $result);
}
print_r($result);
结果:
Array
(
[0] => 8
[1] => 8
[2] => 8
[3] => 8
[4] => 5
[5] => 5
[6] => 5
[7] => 4
)
还可以使用for循环:
<?php
$products = ["4", "5", "8"];
$qty = ["1", "3", "4"];
$result = [];
foreach ($qty as $key => $q) {
for ($i=0; $i < $q; $i++) {
$result[] = $products[$key];
}
}
print_r($result);