簡體   English   中英

PHP如何結合到數組值

[英]PHP how to combine to array values

我有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“]的幫助

使用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
)

https://3v4l.org/Rd4iR

也可以使用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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM