【问题标题】:PHP how to combine to array valuesPHP如何组合到数组值
【发布时间】:2018-12-27 14:02:16
【问题描述】:

我有一个包含 2 个数组的列表,

 [ "4", "4"] - array of product id .
 [ "1", "2"] - array of qty.

如果 qty_array 中的数量为“2”,我只想将 array_product 合并为 ["4","4","4"] 就像 qty 为 3 我想像 ["4" ,"4","4","4"] 请帮忙

【问题讨论】:

    标签: php arrays for-loop arraylist multidimensional-array


    【解决方案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
    )
    

    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);
    

    【讨论】:

    • 哇,太好了,谢谢@Lawrence Cherone。但是在这一行中,你提到 0 不理解-> $result = array_merge(array_fill(0, $qty[$key], $product), $result);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多