Sorting Multi-Dimensional Arrays in PHP 5
First, please excuse me if this is not clear. English is not my first language, though I have tried very hard to make this as intelligible as possible. I am having trouble sorting a multi-dimensional array in PHP. I have reviewed the various array functions on php.net and w3schools, but am still having difficulty.
I have a multi-dimensional array in this form:
$test_array[$counter]['post_id']
$test_array[$counter]['votecount']
$test_array[$counter]['content']
I am trying to sort the array by votecount, so that the post开发者_如何学运维 id with the highest votecount is first and then descends from there. I want to get it into a form such as below:
Votes: 10
Post ID: 4
Content: hhgjhg
Votes: 7
Post ID: 26
Content: fhghg
Votes: 6
Post ID: 15
Content: ytryrd
Use usort function http://php.net/manual/en/function.usort.php
I know it has something to do with this function call. I am also having the same sort of problem, but I think my code is wrong with my array. Look into this function and maybe it will help you. This is added with your array code when the script is processed.
function compare($x, $y)
{
if ($x[1] == $y[1])
{
retun 0;
}
else if ($x[1] < $y[1])
{
return -1;
}
else
{
return 1;
}
}
uasort($products, 'compare');
Try below code
function custom_sorting($a, $b)
{
if ($a['votecount'] == $b['votecount']) {
return 0;
}
return ($a['votecount'] > $b['votecount']) ? -1 : 1;
}
usort($test_array, "custom_sorting");
Working Example
function custom_sorting($a, $b)
{
if ($a['votecount'] == $b['votecount']) {
return 0;
}
return ($a['votecount'] > $b['votecount']) ? -1 : 1;
}
$counter = 0;
$test_array[$counter]['post_id'] = 1;
$test_array[$counter]['votecount'] = 15;
$test_array[$counter]['content'] = "1-15";
$counter = 1;
$test_array[$counter]['post_id'] = 2;
$test_array[$counter]['votecount'] = 18;
$test_array[$counter]['content'] = "2-18";
$counter = 2;
$test_array[$counter]['post_id'] = 3;
$test_array[$counter]['votecount'] = 10;
$test_array[$counter]['content'] = "3-10";
usort($test_array, "custom_sorting");
print_r($test_array);
精彩评论