我在一个数组中有很多数组,我想通过两个争论对数组中的数组进行排序。这两个参数在手上是真的还是假的,另一方面是unix时间戳。这是一个例子:
array(3) => {
array(3) { ["Sticky"]=> bool(true) ["Timestamp"]=> int(1507696669) ["Title"]=> string(12) "TestArtikel2" }
array(3) { ["Sticky"]=> bool(false) ["Timestamp"]=> int(1507696645) ["Title"]=> string(12) "TestArtikel1" }
array(3) { ["Sticky"]=> bool(true) ["Timestamp"]=> int(1507688257) ["Title"]=> string(4) "Home" }
}
我希望按最新的时间戳排序。但是,我想要在false数组之前包含true的所有数组。最后它应该是这样的:
array(3) => {
array(3) { ["Sticky"]=> bool(true) ["Timestamp"]=> int(1507696669) ["Title"]=> string(12) "TestArtikel2" }
array(3) { ["Sticky"]=> bool(true) ["Timestamp"]=> int(1507688257) ["Title"]=> string(4) "Home" }
array(3) { ["Sticky"]=> bool(false) ["Timestamp"]=> int(1507696645) ["Title"]=> string(12) "TestArtikel1" }
}
我现在的问题是,我该怎么做?我有点不知道,抱歉..
这个不起作用:
foreach ($arr as $key => $row) {
$bool[$key] = $row["Sticky"];
$time[$key] = $row["Timestamp"];
}
$allNews = array_multisort($bool, SORT_DESC, $time, SORT_DESC, $allNews);
foreach($allNews as $article){
var_dump($article);
echo "<br>";
}
亲切的问候
答案 0 :(得分:1)
以下是您的代码:
$arr = array(
array(0=>TRUE,1=>1507696669,2=>"TestArtikel2"),
array(0=>FALSE,1=>1507696645,2=>"TestArtikel1"),
array(0=>TRUE,1=>1507688257,2=>"Home")
);
var_dump($arr); // your array
foreach ($arr as $key => $row) {
$bool[$key] = $row[0];
$time[$key] = $row[1];
}
array_multisort($bool, SORT_DESC, $time, SORT_DESC, $arr);
var_dump($arr); // Check your sorted array
OR
$arr = array(
array(0=>TRUE,1=>1507696669,2=>"TestArtikel2"),
array(0=>FALSE,1=>1507696645,2=>"TestArtikel1"),
array(0=>TRUE,1=>1507688257,2=>"Home")
);
var_dump($arr); // your array
array_multisort(array_column($arr, 0), SORT_DESC, array_column($arr, 1), SORT_DESC, $arr);
var_dump($arr); // Check your sorted array
输出我得到的内容与您想要的一样:
array (size=3)
0 =>
array (size=3)
0 => boolean true
1 => int 1507696669
2 => string 'TestArtikel2' (length=12)
1 =>
array (size=3)
0 => boolean false
1 => int 1507696645
2 => string 'TestArtikel1' (length=12)
2 =>
array (size=3)
0 => boolean true
1 => int 1507688257
2 => string 'Home' (length=4)
array (size=3)
0 =>
array (size=3)
0 => boolean true
1 => int 1507696669
2 => string 'TestArtikel2' (length=12)
1 =>
array (size=3)
0 => boolean true
1 => int 1507688257
2 => string 'Home' (length=4)
2 =>
array (size=3)
0 => boolean false
1 => int 1507696645
2 => string 'TestArtikel1' (length=12)
<强>已更新强>
$allNews = array(
array("Sticky"=>TRUE,"Timestamp"=>1507696669,"Title"=>"TestArtikel2"),
array("Sticky"=>FALSE,"Timestamp"=>1507696645,"Title"=>"TestArtikel1"),
array("Sticky"=>TRUE,"Timestamp"=>1507688257,"Title"=>"Home")
);
var_dump($allNews);
array_multisort(array_column($allNews, "Sticky"), SORT_DESC, array_column($allNews, "Timestamp"), SORT_DESC, $allNews);
foreach($allNews as $article){
var_dump($article);
echo "<br>";
}
// var_dump($allNews);