我看到有很多用于排序陣列的檔案,但我發現的只是對陣列中的現有值進行排序。
就我而言,我需要在包含多個陣列的元資料中對陣列本身進行排序。我想按照它們創建的相反順序對它們進行排序。
例子:
$datacomments = get_post_meta($product_id, 'propina5', false);
echo print_r($datacomments);
//Result:
Array ( [0] => Array ( [date] => 30-11-2021 13:38 [id] => 2 [rating] => 4 [comment] => bala bla bla bla bla [perce] => 10 )
[1] => Array ( [date] => 30-11-2021 13:38 [id] => 2 [rating] => 4 [comment] => bala bla bla bla bla [perce] => 10 )
[2] => Array ( [date] => 30-11-2021 13:40 [id] => 2 [rating] => 5 [comment] => bla bla bla bla [perce] => 10 )
[3] => Array ( [date] => 30-11-2021 13:41 [id] => 2 [rating] => 3 [comment] => bla bla bla bla bla [perce] => 5 ) ) 1
我有 3 個陣列 [0], [1], [2] 和 [3] 在創建時默認排序。但是我需要以相反的順序對它們進行準確排序,因為我的意圖是最近的那些首先出現而不是相反。
好吧,我找不到檔案或看不到它是否在官方 php 或 w3school 中,在這種情況下我通常會在其中查找如何排序。
有什么建議嗎?從已經非常感謝你。
uj5u.com熱心網友回復:
$reversed = array_reverse($input);
檔案:https : //www.php.net/manual/en/function.array-reverse.php
如果這個陣列是從資料庫查詢的結果,你可以使用ORDER BYsql 中的語法來準確地獲得你需要的。
uj5u.com熱心網友回復:
這將按每個子陣列的日期值降序排序:
$arr = [
[ 'date' => '29-11-2021 22:32', 'id' => 2, 'rating' => 4, 'comment' => 'bla bla bla', 'perce' => 10 ],
[ 'date' => '29-11-2021 22:35', 'id' => 8, 'rating' => 4, 'comment' => 'bla bla bla', 'perce' => 10 ],
[ 'date' => '29-11-2021 22:45', 'id' => 6, 'rating' => 4, 'comment' => 'bla bla bla', 'perce' => 10 ]
];
usort($arr, static fn(array $arr1, array $arr2): int => -($arr1['date'] <=> $arr2['date']));
相同的代碼也適用于 DateTime 物件:
$arr = [
[ 'date' => new DateTime('29-11-2021 22:32'), 'id' => 2, 'rating' => 4, 'comment' => 'bla bla bla', 'perce' => 10 ],
[ 'date' => new DateTime('29-11-2021 22:35'), 'id' => 8, 'rating' => 4, 'comment' => 'bla bla bla', 'perce' => 10 ],
[ 'date' => new DateTime('29-11-2021 22:45'), 'id' => 6, 'rating' => 4, 'comment' => 'bla bla bla', 'perce' => 10 ]
];
usort($arr, static fn(array $arr1, array $arr2): int => -($arr1['date'] <=> $arr2['date']));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/370099.html
上一篇:在woocommerce的單個產品頁面上使用wp_enqueue_script的Javascript和WordpressUncaughtSyntaxError
