查找重复的数组值并有条件地删除

时间:2012-04-06 08:12:31

标签: php arrays multidimensional-array

我有一个像这样的多维数组:

$orders = array(
  array(
    'id' => '123',
    'name' => 'John',
    'lastname'=>'Carter',
    'rate' => '1.0'
  ),
  array(
    'id' => '546',
    'name' => 'Ben',
    'lastname'=>'Wall',
    'rate' => '0.25'
  ),
  array(
    'id' => '666',
    'name' => 'John Bow',
    'lastname'=>'Porter',
    'rate' => '0.25'
  ),
  array(
    'id' => '156',
    'name' => 'John',
    'lastname'=>'Carter',
    'rate' => '0.5'
  )
);

并且想要创建一个将删除重复行的函数< 1.0。结果数组应为:

$orders = array(
  array(
    'id' => '123',
    'name' => 'John',
    'lastname'=>'Carter',
    'rate' => '1.0'
  ),
  array(
    'id' => '546',
    'name' => 'Ben',
    'lastname'=>'Wall',
    'rate' => '0.25'
  ),
  array(
    'id' => '666',
    'name' => 'John',
    'lastname'=>'Porter',
    'rate' => '0.25'
  )
);

2 个答案:

答案 0 :(得分:0)

编辑:第二个好的版本:http://ideone.com/zJ8vj


“重复”是什么意思 - 相同的“费率”? Bellow示例删除具有相同'rate'和'rate'的重复订单< 1.0。 这是你需要的吗?

$tmpOrders = array();
foreach($orders as $order) {
    // Check only rate < 1.0
    if((float)$order['rate'] < 1.0) {
        // Check duplicate
        $exists = false;
        foreach($tmpOrders as $tmp) {
            if($tmp['rate'] == $order['rate']) {
                $exists = true;
                break;
            }
        }
        // Add if rate not exists
        if(!$exists) {
            $tmpOrders[] = $order;
        }
    }
    // Add all with rate >= 1.0
    else {
        $tmpOrders[] = $order;
    }
}
$orders = $tmpOrders;

echo "<pre>";
print_r($orders);
echo "<pre>";

结果:

Array
(
    [0] => Array
        (
            [id] => 123
            [name] => John
            [lastname] => Carter
            [rate] => 1.0
        )

    [1] => Array
        (
            [id] => 546
            [name] => Ben
            [lastname] => Wall
            [rate] => 0.25
        )

    [2] => Array
        (
            [id] => 156
            [name] => John
            [lastname] => Carter
            [rate] => 0.5
        )

)

答案 1 :(得分:0)

不是很漂亮和速度,但可行的解决方案:

$a = array(...); // Your array

$hashstack = array_map(function($value) { return md5($value['name'] . $value['lastname']); }, $a);
$result = array_filter($a, function($value) use ($hashstack)
{
    if ((float)$value['rate'] < 1.0) {
        $count = 0;
        foreach ($hashstack as $hash) {
            if (md5($value['name'] . $value['lastname']) == $hash) {
                $count++;
            }
        }
        if ($count > 1) {
            unset($value);
            return;
        }
    }
    return $value;
});

结果与你的相同。