0

I want to update an array inside foreach I tried this two code :

code 1 :

 foreach ($listOrders as $k => $order) {

    foreach ($listOrders as $key => $o) 
    {
      if ($o["id_order"] == $order["id_order"])
      {
         unset($listOrders[$key]);
      }
    }

in this codeunset is not working

code 2 :

     foreach ($listOrders as $k => &$order) {

     foreach ($listOrders as $key => $o) 
     {
        if ($o["id_order"] == $order["id_order"])
        {
           unset($listOrders[$key]);
        }
     }

If I use & with $order $listOrders will not returned all data that I want.

Sabra
  • 177
  • 2
  • 19
  • sorry but `$listOrders == $listOrders` you code always return empty array, you can update code, or this is a error, – Naumov Oct 08 '18 at 15:52
  • 1
    Why are you iterating through the list twice? – aynber Oct 08 '18 at 15:52
  • @aynber the OP needs to loop twice because in the column (or field) "o" it can have the value of the column (or field) "order" maybe... and those will be the same in different rows? – Goikiu Oct 08 '18 at 15:54
  • I want to delete other rows from the list with same id_order – Sabra Oct 08 '18 at 15:54
  • Take a look at `array_map` http://docs.php.net/manual/da/function.array-map.php there is also `array_filter`. Map returns an array of the same size with the value "swapped" (as a new array) with the outcome of the function, filter, returns an array filtered by the outcome of the function. – Alexander Holman Oct 08 '18 at 16:09

2 Answers2

0

Your error should be here

  foreach ($listOrders as $k => &$order) { 
                                ^

Remove &

Also you are iterating through your $listOrders twice with your code, won't your array list always be empty after the iteration is finished?

Kebab Programmer
  • 1,213
  • 2
  • 21
  • 36
0

If you are simply trying to get a list of the orders in the list, you can use array_column() to index the list by id_order. As you can only ever have 1 entry in an array with a particular key, this will end up with the last entry with a particular order id in the array...

$uniqueList = array_column(listOrders, null, "id_order");

If you just need the list without the index, you can use array_values() to re-index the list.

$uniqueList = array_values(array_column(listOrders, null, "id_order"));
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • Canonical, if you feel your advice is most appropriate: [Filter/Remove rows where column value is found more than once in a multidimensional array](https://stackoverflow.com/q/45603614/2943403) – mickmackusa May 14 '23 at 06:00