过滤PHP数组,以便只保留唯一记录
我有一个PHP数组:过滤PHP数组,以便只保留唯一记录,php,arrays,Php,Arrays,我有一个PHP数组: array (size=9753) 0 => array (size=3) 'brand' => string 'Brand #1' (length=8) 'name' => string 'Customer #13' (length=12) 'total' => string '93.00' (length=5) 1 => array (size=3) 'brand'
array (size=9753)
0 =>
array (size=3)
'brand' => string 'Brand #1' (length=8)
'name' => string 'Customer #13' (length=12)
'total' => string '93.00' (length=5)
1 =>
array (size=3)
'brand' => string 'Brand #1' (length=8)
'name' => string 'Customer #23' (length=12)
'total' => string '77.00' (length=5)
2 =>
array (size=3)
'brand' => string 'Brand #1' (length=8)
'name' => string 'Customer #32' (length=12)
'total' => string '98.00' (length=5)
...
我想对其进行过滤,以便每个独特品牌(总共有100个品牌)只保留总值最高的记录。此样本的操作结果应为:
0 =>
array (size=3)
'brand' => string 'Brand #1' (length=8)
'name' => string 'Customer #32' (length=12)
'total' => string '98.00' (length=5)
...
作为品牌#1的总数最高
这是一个迭代整个数组的问题,每个品牌只留下一个记录——总数最高的一个
我已经尽了最大的努力,但没有做到这一点。我想到的代码是:
$c = count($ordersData);
for($i=1; $i<$c; $i++) {
if($ordersData[$i]['brand'] == $ordersData[$i-1]['brand']
&& $ordersData[$i]['total'] > $ordersData[$i-1]['total']) {
unset($ordersData[$i-1]);
}
}
$c=count($ordersData);
对于($i=1;$i$ordersData[$i-1]['total']){
未设置($ordersData[$i-1]);
}
}
,但它不会删除所有应删除的记录
非常感谢您的建议。因此,您最好的选择似乎就是像您所做的那样,以$ordersData格式循环所有记录。但是,您的逻辑有点古怪,仅将ordersdata合计与上一个已检查订单的合计进行比较
相反,您可能希望启动一个新数组,并根据品牌名称添加/覆盖值。也许是这样的:
<?php
$results = array();
foreach($ordersData as $order) {
$brand = $order['brand'];
$total = $order['total'];
// If an order of this brand has already been tracked
if(array_key_exists($brand, $results)) {
// and the total of the current order is greater than what we have recorded
if($results[$brand]['total'] < $total) {
// Then let's replace it!
$results[$brand] = $order;
}
} else {
// Never added this brand before? Add it then
$results[$brand] = $order;
}
}
您可以按总计、升序对数组进行排序,然后创建按品牌索引的临时数组(这样键将被稍后(更高)的值覆盖),然后使用数组_值获取数字索引数组:
usort($array, function($a, $b) {
return $b['total'] - $b['total'];
});
$temp=[];
foreach($array as $element) $temp[$element['brand']]=$element;
$out = array_values($temp);
我还想出了另一种方法。我把它粘贴在这里只是为了参考(这是我最初的尝试,改进了)
$c=count($ordersData);
//让我们遍历整个数组
对于($i=0;$i),此解决方案不会返回正确的结果。$out数组表明品牌#1的最高阶值为93.00,实际上是195,00。嗨,这非常有效。感谢您的帮助。除此之外,这也是一个很好的教训。
$c = count($ordersData);
// Let's iterate through the whole array
for($i=0; $i<$c; $i++) {
// Save the current brand being checked
$currentBrand = $ordersData[$i]['brand'];
// If we can still check against the next record and the this is still the same brand..
if (key_exists($i+1, $ordersData) && $ordersData[$i]['brand'] == $ordersData[$i+1]['brand']) {
// If the next order value for the current brand is higher..
if ( $ordersData[$i]['total'] < $ordersData[$i+1]['total'] ) {
//Let's save/overwrite the higher order for the current brand
$results[$currentBrand] = $ordersData[$i+1];
}
}
}