开发者

Deduplicating multidimensional array [duplicate]

开发者 https://www.devze.com 2023-03-18 15:33 出处:网络
This question already has answers here: 开发者_如何学CFilter multidimensional array by column and retain rows with first-occurring unique column value [duplicate]
This question already has answers here: 开发者_如何学C Filter multidimensional array by column and retain rows with first-occurring unique column value [duplicate] (4 answers) Closed 1 year ago.

I have a multidimensional array returned by PDO after a query and i'm having a few duplicate results. They're not entirely duplicate, but only one key is duplicate. So:

[0] => 
  'id' => 2,
  'test' => 'My test',
[1] => 
  'id' => 2,
  'test' => 'Another test',
[2] => 
  'id' => 3,
  'test' => 'My tests',

I want to remove the duplicate entries with the same ID value. How can i do this?


Change your query to use GROUP BY id

But in general if it is an id , it should not be allowed to be duplicate.


You can create a new array with the PDO results...

$newArray = array();
foreach ($pdoArray AS $result) {
    if (isset($newArray[$result['id']])) {
        continue; }
    $newArray[$result['id']] = $result['test'];
}

What this does is adds things to a new array, with the id bing the new array's key. If it finds an array with the same key, it just skips it.

This is a simple answer, you would probably want checks to make sure you get the right value (which of the two IDs do you want to keep?)

Alternatively, if you don't want to keep any of them, build the array, but in addition of doing a continue; you could add the id to a new array (a delete array). Then once the first loop is done, loop thru the delete array and delete the keys:

$newArray = array();
$delete = array();
foreach ($pdoArray AS $result) {
    if (isset($newArray[$result['id']])) {
        $delete[] = $result['id'];
        continue; }
    $newArray[$result['id']] = $result['test'];
}
foreach ($delete AS $del) {
    unset($newArray[$del]); }

OR you can add the ID to the delete arrays key (rather than value) and then do an array_diff_key().

But, it looks to me that you need to re-think your database structure... why do you have duplicate IDs?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号