简体   繁体   English

按内部数组的键对php中的多维数组进行排序

[英]sort multidimensional array in php by key of inner array

I want to sort the Job titles by timestamp "1357894278"我想按时间戳“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!那么如何按 1352796106、1352745201、1357894278 对职位进行排序,谢谢! Wait for the help等待帮助

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. usort按自定义比较函数排序。

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.新的 map 数组是一个非常简单的结构,它只包含关于我的另一个结构的必要信息,足够快速索引和快速排序的信息。

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.这一切都取决于您计算时间成本,并根据数据类型的复杂性和大小确定它对您来说是否昂贵。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM