1

i have sorted an array of travel products by price . i'd like to move the products with a price =0 at the end of the list.

Here is what i have tried:

        for($i = 0; $i < count($mes_voyages); ++$i) {

            if($mes_voyages[i]['prix']==0) 
            {

                array_push($mes_voyages,$mes_voyages[i]);
                unset($mes_voyages[i]);

            }

        }
7
  • 3
    This is probably pseudo-code, but in case you didn't know: PHP variables start with $. Commented Nov 6, 2013 at 16:12
  • oops i got tired ;) thanx...it works now with $i Commented Nov 6, 2013 at 16:18
  • 1
    It happens. Glad to know you got it working :) Commented Nov 6, 2013 at 16:23
  • You will skip every item that comes after an item with price 0 this way ;-) Commented Nov 6, 2013 at 16:23
  • so what is the problem of your code? Commented Nov 6, 2013 at 16:25

2 Answers 2

3

So that will be:

$mes_voyages = array_merge(
   array_filter($mes_voyages, function($item){ return $item['prix']!=0; }),
   array_filter($mes_voyages, function($item){ return $item['prix']==0; })
);
Sign up to request clarification or add additional context in comments.

1 Comment

2

There's a much cleaner solution:

usort($mes_voyages, function($a,$b) {
     if ($a["prix"] === 0 && $a["prix"] != $b["prix"]) return 1;
});

3 Comments

Hm. Not sure that will do the stuff. Sorting callback function should return full set -1 or 0 or 1 for proper result. That need to be tested properly
it does not work combined with my previous treatment to the array which is function cmp($a, $b) {if ($a["prix"] == $b["prix"]) { return 0; } return ($a["prix"] < $b["prix"] ) ? -1 : 1; } usort($mes_voyages, "cmp");
2-way return values in usort()'s callback will result in more iterations under the hood as more ties will need to be broken. usort()'s callback should always return the result of a 3-way comparison.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.