2016-03-24 12 views
-1

I mit einer Struktur ein Array haben wie diese $ product_array Probe =php usort mehrdimensionales Array, um nach Preis aufsteigend

[0] => Array 
     (
      [title] => M-SPA Super Camaro B-150 6-Person Inflatable Bubble Spa 
      [image] => http://ecx.images-amazon.com/images/I/41F6FuitoYL._SL160_.jpg 
      [link] => http://www.amazon.com/stuff 
      [price] => 960.01 
      [merchant] => amazon 
      [discount] => 16 
      [brand] => M-SPA 
     ) 

    [1] => Array 
     (
      [title] => M Spa Model B-130 Camaro Hot Tub, 71 by 71 by 28-Inch, Gray 
      [image] => http://ecx.images-amazon.com/images/I/41zQwjaPqOL._SL160_.jpg 
      [link] => http://www.amazon.com/stuff 
      [price] => 695.01 
      [merchant] => amazon 
      [discount] => 
      [brand] => M-SPA 
     ) 

    [2] => Array 
     (
      [title] => M-SPA B-121 4-Person Inflatable Bubble Spa, Castello 
      [image] => http://ecx.images-amazon.com/images/I/41gnYSSVD5L._SL160_.jpg 
      [link] => http://www.amazon.com/stuff 
      [price] => 1,016.25 
      [merchant] => amazon 
      [discount] => 
      [brand] => M-SPA 
     ) 

ich nicht dieses Array mit dem Preis der niedrigsten zur höchsten bestellen .. Dieser Code ist nicht Arbeits

function order_by_price($a, $b) { 
    if ($a['price'] == $b['price']) { 
     return 0; 
    } 
    return ($a['price'] < $b['price']) ? -1 : 1; 
} 
usort($product_array,order_by_price); 

Was Dank I

+0

Was das Ergebnis ist, dass Sie zurück erhalten? – Ohgodwhy

+0

Mögliches Duplikat von [Sortieren eines Satzes mehrdimensionaler Arrays nach Array-Elementen] (http://stackoverflow.com/questions/2915705/sort-a-set-of-multidimensional-arrays-by-array-elements) –

Antwort

0

Sie haben eine nicht-gut ausgebildet numerischen va am fehlt lue im letzten Array-Element ... [price] => 1,016.25 ....
Es ist ein "Geldformat" und sollte als eine Zeichenfolge dargestellt werden: [price] => "1,016.25".
Außerdem gibt es eine gewisse Vorsicht bei usort Parameter:

Caution: Zurückgeben nicht ganzzahlige Werte aus der Vergleichsfunktion, wie Schwimmer, wird in einem internen gegossenen auf ganzzahlige der Rückkehr des Rückruf führen Wert. So werden Werte wie 0,99 und 0,1 beide auf einen ganzzahligen Wert von 0 umgewandelt, der solche Werte wie gleich vergleicht.

Nach ordnungsgemäßer Ersatz von (Formatierung) Code ändern, wie unten dargestellt:

function order_by_price($a, $b) { 
    $floats = str_replace(",", "", [$a['price'], $b['price']]); 
    return ($floats[0] == $floats[1])? 0 : (($floats[0] < $floats[1]) ? -1 : 1); 
} 

usort($product_array,"order_by_price"); 

Die oben wird wie erwartet ...