PHP: Compare repeated items from a list and discard the one from the highest date

Asked

Viewed 29 times

-2

Good evening, I need some help with the code below:

  • Inside the variable '$data' I have an array where the id repeats with different dates, I need to discard one of the two arrays repeated with the same 'id', keeping the lowest date, IE, the end result would be:

"Array ( [0] => Array ( [id] => 12 [date] => 2020-07-02 ) , [1] => Array ( [id] => 13 [date] => 2020-06-10 ) ) "

  • I’ve tried everything a little at first I’m working with the idea of loop inside loop, to sweep and compare, but as you can see I’m missing something;
<?php
$dados =     [array("id" =>12, "data"=>"2020-07-02"),
            array("id" =>13, "data"=>"2020-06-10"),
            array("id" =>13, "data"=>"2020-06-15"),
            array("id" =>12, "data"=>"2020-05-12")];
$total = count($dados);
foreach($dados as $item){
    for($i=1; $i < $total; $i++){
        if($item['id'] == $dados[$i]['id']){
            if(strtotime($item['data']) <= strtotime($dados[$i]['data'])){
                unset($dados[$i]);
                $dados = array_values($dados);
                $total = count($dados);

            }    
        }    
    }    
}
print_r($dados);

Array ( [0] => Array ( [id] => 12 [data] => 2020-07-02 ) ) //resultado

1 answer

-1

Solution shown by: Israel Lemes, Comunicplus

$dados =    [array("id" =>12, "data"=>"2020-07-02"),
            array("id" =>13, "data"=>"2020-06-10"),
            array("id" =>13, "data"=>"2020-06-15"),
            array("id" =>12, "data"=>"2020-05-12")];

$arraySimples = $resultado = array();
foreach($dados as $item){
    $id = $item['id'];
    $data = $item['data'];
    if(@$arraySimples[$id]) {
        if($arraySimples[$id] > $item['data']) {
            $arraySimples[$id] = $arraySimples[$id] = $item['data'];
        }
    } else {
        $arraySimples[$id] = $item['data'];
    }
    $dados2[] = $arraySimples[$id];
}
foreach($arraySimples as $key => $array){
    $resultado[] = array('id' => $key, 'data' => $array);
}



print_r($arraySimples);
print_r($resultado);

Thank you, same fellow, I sure learned from you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.