Ich versuche, meine Objekt-Array basierend auf minimal SUM
zu sortieren. Dies funktioniert, aber ich möchte meiner usort-Funktion einen weiteren Vergleich hinzufügen, der ein Objekt vorzieht, das einen Wert true hat. Meine Objekte:PHP sort Objekt mit usort basierend auf zwei Werten
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
Und wenn ich diese sort
ist die Reihenfolge Basket[34],Basket[35],Basket[33]
.
Aber ich möchte Basket[35],Basket[33]
und am Ende Basket[34]
, weil er 1 Produkt hat, die nicht existiert.
Also ich möchte basierend auf Produkt Existenz und dann sort
von bestellen. Ich habe dies, aber es funktioniert nicht:
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 as $product) {
if(!$product->exist) {
$unfinded_a++;
}
}
foreach ($b->products as $product) {
if(!$product->exist) {
$unfinded_b++;
}
}
if ($unfinded_a != 0 || $unfinded_b != 0)
return $unfinded_b > $unfinded_a;
});
möglich ist, dies zu tun mit usort
, oder ich habe array_multisort
zu benutzen?
Vielen Dank für Ihre Antwort, aber Ich komme nicht gut zur Ruhe. Dies funktioniert nicht: usort ($ h_basket [$ i], Funktion ($ a, $ b) {return $ a-> Summe> $ b-> Summe;}); usort ($ h_basket [$ i], function ($ a, $ b) { $ existiert = count ( array_filter ( $ a-> Produkte, Funktion ($ Produkt) { return $ produkt-> existieren; } ) )/count ($ a-> Produkte); exists2 $ = count ( array_filter ( b- $> Produkte, Funktion ($ Produkt) { return $ produkt-> existieren; } ) )/count ($ b-> products); return $ exists2> $ exists; }); – Michal