How to remove duplicate elements in a multidimensional matrix

Asked

Viewed 25 times

0

Could someone please help me, as I do to remove the elements of the duplicated array taken into account the key "Name", however returning from the duplicated Names which has the longest date

<?

// MEU ARRAY 
$array =  [
  0 => array:4 [
    "Nome" => "Bruno"
    "Modalidade" => "AA , JJ , HHHH"
    "Valor" => "30.00"
    "Data Pagamento" => "2020-07-04"
  ]
  1 => array:4 [
    "Nome" => "Alice Costa"
    "Modalidade" => "AA , JJ , HHHH"
    "Valor" => "600.00"
    "Data Pagamento" => "2020-08-04"
  ]
  2 => array:4 [
    "Nome" => "Alice Costa"
    "Modalidade" => "AA , JJ , HHHH"
    "Valor" => "600.00"
    "Data Pagamento" => "2020-09-04"
  ]
  3 => array:4 [
    "Nome" => "Jamir"
    "Modalidade" => "AA , TESTE"
    "Valor" => "50.00"
    "Data Pagamento" => "2020-06-04"
  ]
  4 => array:4 [
    "Nome" => "Jamir"
    "Modalidade" => "AA , TESTE"
    "Valor" => "200.00"
    "Data Pagamento" => "2020-10-04"
  ]
];

// RESULTADO ESPERADO

$array =  [
  0 => array:4 [
    "Nome" => "Bruno"
    "Modalidade" => "AA , JJ , HHHH"
    "Valor" => "30.00"
    "Data Pagamento" => "2020-07-04"
  ]
  1 => array:4 [
    "Nome" => "Alice Costa"
    "Modalidade" => "AA , JJ , HHHH"
    "Valor" => "600.00"
    "Data Pagamento" => "2020-09-04"
  ]
  2 => array:4 [
    "Nome" => "Jamir"
    "Modalidade" => "AA , TESTE"
    "Valor" => "200.00"
    "Data Pagamento" => "2020-10-04"
  ]
];

?> 

1 answer

0

You can turn your array in a Collection and use the methods groupBy and map

$users = collect($array)->groupBy('Nome')->map(static function($users) {
    return $users->last();
});

It is also possible to filter the query, but for that you first need to know how the query is being made.

  • good afternoon Erlon, unfortunately did not give, converted into collection but still continues to pick up those who have the lowest payment date, the idea was to bring those who have the latest date

  • In this case, even with Collections vc can use``groupBy('name')e em seguida usar omap()` to catch the last feather, but the best is to know how this query is being made, it is always faster to use the bank and make a very specific query

  • Unfortunately this approach I will have to perform in the code, although in the bank really be faster, because in the situation I have to perform I will not be able to do for the bank, but you can elaborate an example for kindness of how would use the map ?

Browser other questions tagged

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