2016-03-26 2 views
-1

Ich habe das folgende Array und ich möchte dieses Array in absteigender Reihenfolge auf der Basis des "count" Index-Wertes in PHP sortieren. Ich habe den folgenden Code verwendet, aber es funktioniert nicht für mich. Bitte geben Sie mir einen Hinweis, um das Array in absteigender Reihenfolge zu sortieren.wie zwei dimensionale Array in absteigender Array in PHP zu sortieren?

Array: -

Array ([0] => Array ([text] => this is text [count] => 0) 
     [1] => Array ([text] => this is second text [count] => 2) 
     [2] => Array ([text] => this is third text [count] => 1) 
    ) 

Ich habe den folgenden Code versucht.

function sort_count($a, $b) { 
    return $a['count'] - $b['count']; 
} 
$sorted_array = usort($array, 'sort_count'); 
+2

Es hat bereits eine Lösung hier: http://stackoverflow.com/questions/2699086/sort-multi-dimensional-array-by-value –

Antwort

0

Try this:

Hinweis: Überprüfen der Gleichheit wirkt als zusätzlicher Vorteil.

function sort_count($a, $b) { 
    if ($a['count'] === $b['count']) { 
     return 0; 
    } else { 
     return ($a['count'] > $b['count'] ? 1:-1); 
    } 
} 
$sorted_array = usort($array, 'sort_count'); 

echo "<pre>"; 

print_r($array); 

echo "</pre>"; 

Hoffe, das hilft.

2

aufsteigende ..

usort($your_array, function($a, $b) { 
    return $a['count'] - $b['count']; 
}); 

absteigend ..

usort($your_array, function($a, $b) { 
    return $b['count'] - $a['count']; 
}); 

Example here

+0

Dies wird auf PHP 5.3 oder höher arbeiten. (Anon-Funktionen) Wenn Sie auf einer niedrigeren Version sind. Sie müssen zuerst die Funktion definieren. Wie du es in deinem Beispiel getan hast. – KyleK

+0

wird nicht in absteigender Reihenfolge sortiert – RomanPerekhrest

0

Hier ist die Lösung:

$a1 = array (array ("text" => "this is text", "count" => 0), 
    array ("text" => "this is text", "count" => 1), 
    array ("text" => "this is text", "count" => 2), 
); 
usort($a1 ,sortArray('count')); 
function sortArray($keyName) { 
    return function ($a, $b) use ($keyName) {return ($a[$keyName]< $b[$keyName]) ? 1 : 0; 
    }; 
} 
print_r($a1);