首页 > 解决方案 > php 从旧数组创建新数组

问题描述

在某些情况下,我需要从项目订单中为我的货件进行拆分项目。规则是每 1 批货物的最大重量为 5。这是我的物品订单:

$items = [
    [
        "sku"       => "SKU-A",
        "name"      => "Product A",
        "weight"    => 7,
        "dimension" => "20x30x10"
    ],
    [
        "sku"       => "SKU-B",
        "name"      => "Product B",
        "weight"    => 4,
        "dimension" => "10x10x20"
    ],
];

进行拆分后,我希望结果如下:

// will create new array
// limit weight per shipment max 5kg
$item1 = [
    [
        "sku"       => "SKU-A",
        "name"      => "Product A",
        "weight"    => 5,
        "dimension" => "20x30x10"
    ]
];

$item2 = [
    [
        "sku"       => "SKU-A",
        "name"      => "Product A",
        "weight"    => 2,
        "dimension" => "20x30x10"
    ], // this item from SKU-A where w => 7 - 5 = 2 
    [
        "sku"       => "SKU-B",
        "name"      => "Product B",
        "weight"    => 3,
        "dimension" => "10x10x20"
    ],
];

$item3 = [
    [
        "sku"       => "SKU-B",
        "name"      => "Product B",
        "weight"    => 1,
        "dimension" => "10x10x20"
    ],// this item from SKU-B where w => 7 - 5 = 2 
];

这样做的可能方法是什么?谢谢你。

标签: phparrays

解决方案


@catLovers,我已根据需要制作了此代码...请根据需要即兴创作/优化。

$items = [
             [
                 "sku"       => "SKU-A",
                 "name"      => "Product A",
                 "weight"    => 7,
                 "dimension" => "20x30x10"
             ],
             [
                 "sku"       => "SKU-B",
                 "name"      => "Product B",
                 "weight"    => 4,
                 "dimension" => "10x10x20"
             ],
         ];
        
         $newItems = array();
         for ($x = 0; $x <= count($items)-1; $x++) {
          if ($items[$x]['weight'] > 5) {
             $weight = $items[$x]['weight'];
             $wt =5;
            do {
                $temp = array([
                 'sku'       => $items[$x]['sku'],
                 'name'      => $items[$x]['name'],
                 'weight'    => $wt,
                 'dimension' => $items[$x]['dimension']
                 ]);
                array_push($newItems,$temp);
                $weight=$weight-5;
                if ($weight <=5){ $wt=$weight;}
            
                } while ($weight <= 5);
             echo "<pre>";
             print_r($temp);
             echo "</pre>";
           }
           else {
           array_push($newItems,$items[$x]);
          
          }
         }
         echo "<pre>";
         print_r($newItems);
         echo "</pre>";

推荐阅读