At first - yes, I've tried to find my problem here, but can't make it.
I have a problem with array sorting. I want to use custom array sorting to sort some data taken from DB.
For example, I have array
values: [ 0, 0, 0, 0, 14830, 78426, 0, 0, 0, 0, 0, 0, 6024, 1144, 4438, 19282 ]
And I need to get last 4 (sometimes 3 or 2, so it would be custom) results on the first place in the same order as they are now. And the result should be like:
values: [ 6024, 1144, 4438, 19282, 14830, 78426, 0, 0, 0, 0, 0, 0,]
How can I do that?
I make this array with
while($row=mysql_fetch_array($re))
{
$dates = $row['mon'];
while ($current_month != $dates) {
$current_month = $current_month + 1;
if($current_month == 13)
$current_month = 1;
$data[] = 0;
}
$data[] = intval($row['type']);
$current_month = $dates+1;
}
I take months number as $current_month and using it puts my data in right places. When month have no results it adds 0 in that place. The results should be just 6 and when there's no passing through the years it makes array right, but sometimes it goes wrong like this, so I want to make proper array using custom sorting like I mantioned at first.
So I want to sort this array and with array_slice cut it to 6.
Thanks for help.
$desired_length = 4;
$arr = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14);
$length = count($arr);
$array = array_slice($arr, $length-$desired_length, $desired_length) + array_slice($arr,0,$length-$desired_length);
$svalues = array_slice($values, 4);
rsort(&$svalues);
$array = array_merge(array_slice($values, count($values) - 4, 4), $svalues);
here is an exmaple of custom sort.. I am not sure if I understood your question correctly to help you there.. but this should give u an idea..
var myMultiArray = [ {"Name": "Steve", "Age":41},
{"Name": "Joe", "Age":55},
{"Name": "Robert", "Age":34},
{"Name": "Alex", "Age":35}];
function customMultiSort(a, b) {
return (a['Age'] - b['Age']);
}
myMultiArray.sort(customMultiSort);
document.write(myMultiArray.toSource());