pan*_*hro 5 php arrays sorting
我有一个数组:
Array
(
[product1] => Array
(
[id] => 1
[title] => 'p1'
[extra] => Array(
[date] => '1990-02-04 16:40:26'
)
)
[product2] => Array
(
[id] => 2
[title] => 'p2'
[extra] => Array(
[date] => '1980-01-04 16:40:26'
)
)
[product3] => Array
(
[id] => 3
[title] => 'p3'
[extra] => Array(
[date] => '2000-01-04 16:40:26'
)
)
[product4] => Array
(
[id] => 4
[title] => 'p4'
[extra] => Array(
[date] => '1995-01-04 16:40:26'
)
)
[product5] => Array
(
[id] => 5
[title] => 'p5'
[extra] => Array(
[date] => '1960-01-04 16:40:26'
)
)
...
Run Code Online (Sandbox Code Playgroud)
我需要获取最新日期的 2 个产品并将它们移动到数组的开头。
我已经研究了 multisort 函数,我可以像这样对数组进行排序,但是整个数组将按日期排列,我想保持数组的顺序,但只是增加了最新的 2 行。
我需要从数组中挑选出 2 个最新的(按日期排序),然后将它们移动到数组的开头。所以id的顺序应该是:
3,4,1,2,5
Run Code Online (Sandbox Code Playgroud)
最新的 2 个已经移到数组的前面,其余的仍然按 id 排序。
// Making array with only dates
$dates = array();
foreach ($arr as $key => $item)
$dates[$key] = $item['extra']['date'];
// Sort it by date saving keys
uasort($dates, function($i1, $i2) { return strtotime($i1) - strtotime($i2); });
// Take keys
$dates = array_keys($dates);
// Create array with two needed items
$newarray = array( $dates[0] => $arr[$dates[0]], $dates[1] => $arr[$dates[1]]);
// remove these items
unset($arr[$dates[0]]); unset($arr[$dates[1]]);
// put them in array start
$arr = array_merge($newarray, $arr);
var_dump($arr);
Run Code Online (Sandbox Code Playgroud)