Try this:
function compare($a, $b) {
$ak = array_keys($a);
$bk = array_keys($b);
return ($ak[0] < $bk[0]) ? -1 : 1;
}
usort($ans, "compare");
var_dump($ans);
usort
sorts by a custom comparison function.
Domanda
I want to sort the Job titles by timestamp "1357894278"
<?php
foreach( $jobs as &$job )
{
$cj_date[] = array( strtotime($job->date) => array( $job->title ));
}
foreach ($results['results'] as $result)
{
$in_date[] = array ( strtotime($result['date']) => array ($result['jobtitle']) );
}
$ans[] = array_merge($cj_date,$in_date);
foreach($ans as $a)
{
ksort($a);
print_r($a);
}
?>
By running this this script I got my output as following:
Array( [0] => Array
( [1352796106] => Array
( [0] => JobTitle_1 )
)
[1] => Array
( [1352745201] => Array
( [0] => JobTitle_2 )
)
[2] => Array
( [1357894278] => Array
( [0] => JobTitle_3 )
)
)
So How to sort the Job-Titles by 1352796106, 1352745201, 1357894278 Thanks! Wait for the help
Soluzione
Try this:
function compare($a, $b) {
$ak = array_keys($a);
$bk = array_keys($b);
return ($ak[0] < $bk[0]) ? -1 : 1;
}
usort($ans, "compare");
var_dump($ans);
usort
sorts by a custom comparison function.
Altri suggerimenti
I had a similar problem a while back. I had a much more complex structure. I ended up creating another array as my 'map', and I used it for sorting/indexing.
The new map array was a very simple structure that only contained necessary information about my other structure, just enough information to index quickly and to sort quickly as well.
I am sure there may be other solutions, but this worked for me because I had very large complex structures that will be more expensive to iterate throught if I did not have that extra map structure. It all comes down to you calcuating your time-cost and finding out if it is going to be expensive or not for you depending on the complexity and the size of your data types.