Greg Ostry
Greg Ostry

Reputation: 1231

How to remove duplicates in foreach in php

I'm var_dumping from a sql table something like this:

<?= "<pre>";  ?>
        <?php var_dump($presents); ?>
<?= "</pre>";  ?>

Result:

  [40]=>
  object(stdClass)#44 (7) {
    ["PersNr"]=>
    string(4) "101"
    ["Name"]=>
    string(7) "John"
    ["Typ"]=>
    string(1) "1"
    ["StartTime"]=>
    string(8) "11:43:52"
    ["LastTask"]=>
    string(3) "130"
  }
  [41]=>
  object(stdClass)#45 (7) {
    ["PersNr"]=>
    string(4) "102"
    ["Name"]=>
    string(6) "Maria"
    ["Typ"]=>
    string(1) "1"
    ["StartTime"]=>
    string(8) "08:01:04"
    ["LastTask"]=>
    string(3) "130"
  }
  [42]=>
  object(stdClass)#46 (7) {
    ["PersNr"]=>
    string(4) "103"
    ["Name"]=>
    string(9) "Jane"
    ["Typ"]=>
    string(1) "1"
    ["StartTime"]=>
    string(8) "06:54:15"
    ["LastTask"]=>
    string(3) "140"
  }

I would like to fetch the LastTask and remove the duplicate

<?php foreach($presents as $present) :?>
    <?php echo $present->LastTask ?>
<?php endforeach ?>

With this i get ... 130 130 140 .... Is there a function to remove the duplicates ?

Upvotes: 1

Views: 5179

Answers (3)

Josh
Josh

Reputation: 424

Use your foreach to assign the correct values to an array

$output = array();
foreach($presents as $present){
    $output[] = $present->LastTask;
}

Then use array_unique to filter it.

$result = array_unique($output);

As mentioned in a comment, a better solution might be to alter the query so it uses a GROUP BY to only return unique LastTask values. This would be a better solution if and only if the other information in the query result ($presents) isn't used elsewhere.

Upvotes: 7

iainn
iainn

Reputation: 17433

If you're using PHP 7, you can use array_column to re-index an array of objects using a specified field, which has the side-effect of removing duplicates. The advantage of this approach is that it keeps the full object as part of the array, in case other fields are also needed in your output:

$array = array_column($array, null, 'LastTask'));

See https://eval.in/896268

Upvotes: 0

Lexxusss
Lexxusss

Reputation: 552

function removeDuplicates($array) {
    $arr = [];   
    foreach ($array as $obj) {
       $arr[$obj->LastTask] = $obj;
    }

    return $arr;
}

$presents = removeDuplicates($presents);

or even like this:

function keyBy($array, $field) {
    $arr = [];   
    foreach ($array as $val) {
       $key = is_array($val) ? $val[$field] : $val->{$field};
       $arr[$key] = $obj;
    }

    return $arr;
}

$presents = keyBy($presents, 'LastTask');

Upvotes: 0

Related Questions