首页 > 解决方案 > 根据数组本身中的值复制数组项

问题描述

我试图通过将它们乘以数组中数量的值来复制数组项。例如,我目前有一个数组,其中有一个数量元素,如下所示:

Array
(
    [0] => Array
        (
            [product_id] => 18551
            [quantity] => 1
            [text] => 10
            [category_id] => 52
        )

    [1] => Array
        (
            [product_id] => 15283
            [quantity] => 2
            [text] => 7
            [category_id] => 52
        )

    [2] => Array
        (
            [product_id] => 17756
            [quantity] => 2
            [text] => 7
            [category_id] => 49
        )

    [3] => Array
        (
            [product_id] => 15026
            [quantity] => 1
            [text] => 3
            [category_id] => 49
        )
)

基于上述内容我试图实现的输出将如下所示:

Array
    (
        [0] => Array
            (
                [product_id] => 18551
                [quantity] => 1
                [text] => 10
                [category_id] => 52
            )
    
        [1] => Array
            (
                [product_id] => 15283
                [quantity] => 1
                [text] => 7
                [category_id] => 52
            )
        
        [2] => Array
            (
                [product_id] => 15283
                [quantity] => 1
                [text] => 7
                [category_id] => 52
            )
    
        [3] => Array
            (
                [product_id] => 17756
                [quantity] => 1
                [text] => 7
                [category_id] => 49
            )
    
        [4] => Array
            (
                [product_id] => 17756
                [quantity] => 1
                [text] => 7
                [category_id] => 49
            )
    
        [5] => Array
            (
                [product_id] => 15026
                [quantity] => 1
                [text] => 3
                [category_id] => 49
            )
    )

我的代码如下所示:

foreach ($plants_array as $pa) {
    foreach ($pa as $quantity) {
        $quantity_array = $pa['quantity'];
    }
    $new_array[] = $plants_array * $pa['quantity'];
}

但是这会产生以下错误:不支持的操作数类型

阅读此内容表明该错误是因为我正在尝试对数组项进行多重排列,但这正是我试图实现的目标。

有人能指出我如何实现这一目标吗?

感谢您的时间和帮助。

标签: phparrays

解决方案


我从你的代码中得到了它,它可能不是最有效的,但我认为它有效:

$new_array=[];
foreach ($plants_array as $pa) 
{
    for($i=0;$i<$pa['quantity'];$i++) 
    {
        $new_array[]=['product_id' =>$pa['product_id'],'quantity' => 1,'text' => $pa['text'],'category_id' => $pa['text']];
    }
}

推荐阅读