使用PHP删除重复的数组数据

时间:2014-03-15 08:48:21

标签: php arrays

我想在profile_id重复时从数组中删除数据。 这是我的数组

 $response[0]['profile_id'] = 100; 
 $response[0]['profile_name'] = 'deepu';
 $response[0]['address'] = 'deesdvsdvsdvpu';

 $response[1]['profile_id'] = 101; 
 $response[1]['profile_name'] = 'deepu';
 $response[1]['address'] = 'deesdvsdvsdvpu';


 $response[2]['profile_id'] = 100; 
 $response[2]['profile_name'] = 'deepu';
 $response[2]['address'] = 'deesdvsdvsdvpusdvsdvsdvsdvsdv';

 $response[3]['profile_id'] = 102; 
 $response[3]['profile_name'] = 'desdvsdvepu';
 $response[3]['address'] = 'deesdvsdvsdvpusdvsdvsdvsdvsdsdvsdvv';


 $input = array_map("unserialize", array_unique(array_map("serialize", $response)));

我想要这个输出

   $response[0]['profile_id'] = 100; 
   $response[0]['profile_name'] = 'deepu';
   $response[0]['address'] = 'deesdvsdvsdvpu';

   $response[1]['profile_id'] = 101; 
   $response[1]['profile_name'] = 'deepu';
   $response[1]['address'] = 'deesdvsdvsdvpu';

   $response[3]['profile_id'] = 102; 
   $response[3]['profile_name'] = 'desdvsdvepu';
   $response[3]['address'] = 'deesdvsdvsdvpusdvsdvsdvsdvsdsdvsdvv';

但我无法得到这个。如果有人知道这一点,请帮助我。

2 个答案:

答案 0 :(得分:0)

尝试使用php-function:array_unique

或手动:

$ids = array();

foreach($response as $key => $entry){
  if(in_array($entry['profile_id'], $ids)){
    unset($response[$key]);
  }else{
    $ids[] = $entry['profile_id'];
  }
}

答案 1 :(得分:0)

$new_arr = array_reduce($response, function($t, $v) {
    $profile_id = $v['profile_id'];
    if (!isset($t[$profile_id]))
        $t[$profile_id] = $v;
    return $t;
}, array());
$new_arr = array_values($new_arr); // to get indexes back to 0, 1, 2...