2010-11-19 7 views
1

Voici un exemple du type de résultats pour un appel d'API. Je veux trier ces résultats par prix et garder la structure du tableau. J'ai essayé de nombreux exemples du manuel et du code que j'ai trouvé, mais je n'arrive pas à trouver le bon combo pour le faire fonctionner. J'apprécierais vraiment toute aide.quel tri php à utiliser pour le tableau multidimensionnel et par la valeur «prix»?

array(7) { 
    ["errors"]=> array(0) { } 
    ["warnings"]=> array(1) { 
    [0]=> array(2) { 
     ["code"]=> string(26) "api_class_update_available" 
     ["msg"]=> string(58) "The Api class is now available in version 1.6" 
    } 
    } 
    ["data"]=> array(4) { 
    [0]=> array(3) { 
     ["url"]=> string(7) "http://" 
     ["keyword"]=> string(7) "keyword1" 
     ["price"]=> string(5) "23.99" 
    } 
    [1]=> array(3) { 
     ["url"]=> string(7) "http://" 
     ["keyword"]=> string(7) "keyword2" 
     ["price"]=> string(5) "19.99" 
    } 
    [2]=> array(3) { 
     ["url"]=> string(7) "http://" 
     ["keyword"]=> string(7) "keyword3" 
     ["price"]=> string(5) "29.99" 
    } 
    [3]=> array(3) { 
     ["url"]=> string(7) "http://" 
     ["keyword"]=> string(7) "keyword4" 
     ["price"]=> string(5) "9.99" 
    } 
    } 
    ["countryCode"] => string(2) "US" 
    ["page"] => int(1) 
    ["limit"]=> int(4) 
} 
+0

Quelle est votre approche? –

Répondre

3

Vous pouvez utiliser usort() pour trier la propriété $array['data']

function priceCompare($a, $b) { return $a['price'] - $b['price']; } 
usort($results['data'], 'priceCompare'); 

Ou en PHP 5.3, vous pouvez utiliser une fermeture de sorte que vous n'avez pas besoin de définir une fonction:

usort($results['data'], function($a, $b) { return $a['price'] - $b['price']; }); 
+0

très élégant! +1 – Patrick

+0

brillant! Merci une tonne gnarf !! PHP 5.2.14 était installé, donc le premier exemple a fonctionné parfaitement! – gBarrett

Questions connexes