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 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'
  )
);
4

2 回答 2

0

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


您所说的“重复”-相同的“速率”是什么意思?下面的示例删除具有相同“率”和“率”< 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
        )

)
于 2012-04-06T08:57:30.963 回答
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;
});

结果和你一样。

于 2012-04-06T09:46:07.820 回答