sorting - PHP sort object with usort based on two values -
i'm trying sort object array based on minimal sum
. working, want add usort function comparison, prefer object, have 1 value true. objects:
object(basket)[33] public 'products' => array (size=2) 0 => object(product)[13] public 'name' => string 'name one' (length=8) public 'price' => float 0.75 public 'exist' => boolean true 1 => object(product)[7] public 'name' => string 'name two' (length=8) public 'price' => float 2.39 public 'exist' => boolean true public 'sum' => float 3.14 object(basket)[34] public 'products' => array (size=2) 0 => object(product)[19] public 'name' => string 'name one' (length=8) public 'price' => float 0.75 public 'exist' => boolean true 1 => object(product)[72] public 'name' => string 'name two' (length=8) public 'price' => null public 'exist' => boolean false public 'sum' => float 0.75 object(basket)[35] public 'products' => array (size=2) 0 => object(product)[1] public 'name' => string 'name one' (length=8) public 'price' => float 0.75 public 'exist' => boolean true 1 => object(product)[2] public 'name' => string 'name two' (length=8) public 'price' => float 1.75 public 'exist' => boolean true public 'sum' => float 2.5
and if sort
this, order basket[34],basket[35],basket[33]
.
but want basket[35],basket[33]
, @ end basket[34]
, because has 1 product, doesn't exist.
so want order based on product existation , sort
sum
. have this, doesn't work:
usort($h_basket[$i], function($a, $b) { return $a->sum > $b->sum; }); usort($h_basket[$i], function($a, $b) { $unfinded_a = 0; $unfinded_b = 0; foreach ($a->products $product) { if(!$product->exist) { $unfinded_a++; } } foreach ($b->products $product) { if(!$product->exist) { $unfinded_b++; } } if ($unfinded_a != 0 || $unfinded_b != 0) return $unfinded_b > $unfinded_a; });
is possible usort
, or have use array_multisort
?
to sort "exists" field (and assume greater percentage of carts products exist, higher should sorted)
i suggest use array_filter simple count of how many products have 'exists' vs total e.g.
$exists = count( array_filter( $object->products, function ($product) { return $product->exist; } ) ) / count($object->products);
then compare calculated $exists
value 2 baskets being compared.
to sort multiple fields (exists, , sum) believe you'll need call usort
twice, in reverse order - sort sum
first then exists
Comments
Post a Comment