简体   繁体   English

PHP对多维数组进行排序

[英]PHP Sorting An Multidimensional Array

I am new to PHP and I am unsure as to why my code is not outputting. 我是PHP新手,我不确定为什么我的代码没有输出。 I have everything in place with no errors and everything seems correct. 我一切准备就绪,没有错误,一切似乎都正确。 I am trying to output the names and dates in ascending order while using print_r() to verify the order. 我正在尝试使用print_r()验证顺序时按升序输出名称和日期。 I would appreciate some guidance to this matter as I have no idea where I am going wrong. 我希望能对此问题提供一些指导,因为我不知道我要去哪里错了。

$win = array('Name'=> 
                        array('Jane Doe ', 'Nash Patel ', 'Joe Public '), 
             'Date'=>
                        array('7 October 2015 ', '14 October 2014 ', '12 October 2016 '));

foreach($win as $element => $namedate) {
    echo '<strong>' . $element . '</strong><br>';
    foreach($namedate as $both) {
       echo $both . '<br/>';
    }
}

foreach($win as $c=>$key) {
        $sort_date[] = $key['Date'];
        $sort_name[] = $key['Name'];
    }

    array_multisort($sort_name, SORT_ASC, $sort_date, SORT_ASC, $win);
    print_r($win);

OUTPUT\\ 输出\\

Array ( [Date] => Array ( [0] => 7 October 2015 [1] => 14 October 2014 [2] => 12 October 2016 ) [Name] => Array ( [0] => Jane Doe [1] => Nash Patel [2] => Joe Public ) ) Array([Date] => Array([0] => 2015年10月7日[1] => 2014年10月14日[2] => 2016年10月12日)[Name] => Array([0] => Jane Doe [1 ] => Nash Patel [2] => Joe Public))

I've read the docs and it seems that 我已经阅读了文档,似乎

array_multisort($sort_name, SORT_ASC, $sort_date, SORT_ASC, $win);

means that $win will be sorted by name and date, but sorting by name has bigger priority over date. 表示$ win将按名称和日期排序,但按名称排序比日期优先级更高。

Try adding more Jane Doe with different dates to see that they're sorted with date. 尝试添加更多具有不同日期的Jane Doe ,以查看它们是否按日期排序。

Because you say the arrays don't need to be sorted together here is how to split them and sort them separately. 因为您说不需要将数组排序在一起,所以这里介绍了如何将它们拆分并分别排序。

$win = array('Name'=> 
                    array('Jane Doe ', 'Nash Patel ', 'Joe Public '), 
         'Date'=>
                    array('7 October 2015 ', '14 October 2014 ', '12 October 2016 '));


$dates = $win["Date"]; //split array
$names = $win["Name"]; //split array

usort($dates, "date_sort"); // custom sort on dates
asort($names); // sort names

var_dump($dates);
Var_dump($names);


function date_sort($a, $b) {
    return strtotime($a) - strtotime($b);
}

https://3v4l.org/kLjRh https://3v4l.org/kLjRh

Output: 输出:

array(3) {
  [0]=>
  string(16) "14 October 2014 "
  [1]=>
  string(15) "7 October 2015 "
  [2]=>
  string(16) "12 October 2016 "
}

 array(3) {
  [0]=>
  string(9) "Jane Doe "
  [2]=>
  string(11) "Joe Public "
  [1]=>
  string(11) "Nash Patel "
}

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

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