php - 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
];
这样做的可能方法是什么?谢谢你。
解决方案
@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>";
推荐阅读
- javascript - 拒绝将字符串评估为 JavaScript,因为在以下内容安全策略中,“unsafe-eval”不是允许的脚本来源
- mysql - 如何使用 mysql 选择 DISTINCT 行
- amazon-web-services - AWS EC2 在 2 周后无法 ssh 没有任何变化
- spring - 如何在spring Cacheable中根据响应对象设置ttl
- reactjs - 用户停止输入后运行电子邮件检查
- python-3.x - 处理两个具有相同名称的设备
- python - 检查多个变量是否为 None 并分配第一个不是 None 的变量
- python - 创建 Trial 对象,设置并获取超参数
- reactjs - 通过更新状态来关注受控的 TextField,但也强制更新?
- matplotlib - 在绘制多个图形时添加滚动条以在 PyQt5 中保留图形大小