我有一个包含三列ID,产品代码,库存的数组
如何从阵列中删除旧库存条目?
我可以逐个删除它,但是正在寻找简单的解决方案。
数组
Array
(
[0] => Array
(
[Id] => 1
[ProductCode] => 4353
[TotalStock] => 10
)
[1] => Array
(
[Id] => 1
[ProductCode] => 4354
[TotalStock] => 80
)
[2] => Array
(
[Id] => 1
[ProductCode] => 4353
[TotalStock] => 60
)
[3] => Array
(
[Id] => 1
[ProductCode] => 4355
[TotalStock] => 30
)
[4] => Array
(
[Id] => 1
[ProductCode] => 4353
[TotalStock] => 20
)
[5] => Array
(
[Id] => 1
[ProductCode] => 4356
[TotalStock] => 40
)
)
预期产量
Array
(
[0] => Array
(
[Id] => 1
[ProductCode] => 4354
[TotalStock] => 80
)
[1] => Array
(
[Id] => 1
[ProductCode] => 4355
[TotalStock] => 30
)
[2] => Array
(
[Id] => 1
[ProductCode] => 4353
[TotalStock] => 60
)
[3] => Array
(
[Id] => 1
[ProductCode] => 4356
[TotalStock] => 40
)
)
答案 0 :(得分:2)
我想您只需要覆盖特定productId的子数组(内部数组)即可获取最新信息。我们可以使用ProductCode
作为键来过滤出重复项:
$csv_mod = array(); // initializing variable to store latest values
foreach ($csv as $obj) {
if ( isset($csv_mod[$obj['ProductCode']])
&& $csv_mod[$obj['ProductCode']]['TotalStock'] < $obj['TotalStock'] ) {
// This will overwrite if a duplicate value with higher stock appears
$csv_mod[$obj['ProductCode']] = $obj;
} else {
// First time encountered in the loop
$csv_mod[$obj['ProductCode']] = $obj;
}
}
答案 1 :(得分:1)
排序数组。
sort($products);
由于ID始终相同,因此将按照产品代码升序,然后按TotalStock升序对内部数组进行排序。
然后通过ProductCode重新编制索引。
$newest = array_column($products, null, 'ProductCode');
您将获得每个ProductCode的最后一个条目。
请注意,简单的sort()
取决于要进行排序的列。如果列的顺序改变了,则需要使用usort()
来指定排序顺序。