2010-09-01 7 views
2

Son mon tableau:tableau étrange par numéro

$hello = Array(
[text] => Array([name] => blabla [num] => 10) 
[sometext] => Array([name] => blabla [num] => 2) 
[anytext] => Array([name] => blabla [num] => 1) 
) 

Comment trier ce tableau par [num]?

devrait ressembler à (sur l'écho):

<ul> 
    <li>anytext</li> 
    <li>sometext</li> 
    <li>text</li> 
</ul> 

Merci.

Répondre

5

Utilisation uasort():

<?php 
$hello = array(
    'text' => array('name' => 'blabla', 'num' => 10), 
    'sometext' => array('name' => 'blabla', 'num' => 2), 
    'anytext' => array('name' => 'blabla', 'num' => 1) 
); 

function sort_func($x, $y) { // our custom sorting function 
    if($x['num'] == $y['num']) 
    return 0; // zero return value means that the two are equal 
    else if($x['num'] < $y['num']) 
    return -1; // negative return value means that $x is less than $y 
    else 
    return 1; // positive return value means that $x is more than $y 
} 

uasort($hello, 'sort_func'); 

echo '<ul>'; 
foreach($hello as $key => $value) 
{ 
    echo '<li>'.htmlspecialchars($key).'</li>'; 
} 
echo '</ul>'; 
+0

comment ça marche? – James

+0

Je l'ai réparé maintenant (j'ai d'abord mal interprété votre question ..). – Frxstrem

+0

@WorkingHard: 'uasort()' appellera notre fonction de comparaison ('sort_func()') avec deux paramètres, où notre fonction les compare et dit 'uasort()' qui a la plus grande valeur. Ensuite 'uasort()' trie le tableau en utilisant ceci. – Frxstrem

2

uasort est ce que vous recherchez.

function cmp($a, $b) { 
    if ($a['num'] == $b['num']) { 
     return 0; 
    } 
    return ($a['num'] < $b['num']) ? -1 : 1; 
} 

uasort($hello, 'cmp');