php - 将特定的数组项移动到数组的开头而不改变其余项的顺序

标签 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'
        )
    )
    ...

我需要获取 2 个具有最新日期的产品并将它们移至数组的开头。

我研究了 multisort 函数,我可以像这样对数组进行排序,但是整个数组将按日期排列,我想保持数组的顺序但只是增加最新的 2 行。

我需要从数组中挑选出 2 个最新的(按日期排序),然后将它们移动到数组的开头。所以ids的顺序应该是:

3,4,1,2,5

最新的2个移到了数组的最前面,剩下的还是按照id排序。

最佳答案

不是最优化的实现,而是最直接的:

$array = /* your data */;

$latest = $array;
uasort($latest, function (array $a, array $b) {
    return strtotime($a['extra']['date']) - strtotime($b['extra']['date']);
});
array_splice($latest, 2);

$latestOnTop = array_merge($latest, array_diff_key($array, $latest));

array_splice 操作要求您的数组键实际上是 product1 或类似的;不适用于数字索引,因为它们将被重新编号。如果是这种情况,请使用另一种截断机制。

如果你的数组真的很大,一个完整的排序将不必要地慢。在这种情况下,您应该遍历数组一次,跟踪您可以找到的两个最新项(及其键),然后是 array_diff_keyarray_merge。这实现起来有点困难(留给读者练习),但效率更高。

关于php - 将特定的数组项移动到数组的开头而不改变其余项的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30664662/

相关文章:

php - 对 PHP 的非阻塞 Ajax 请求

php - 如何使用php在邮件功能中发送jquery?

javascript - 合并 "rows"并将有序的 "cols"添加到对象数组

Java 代码审查 : Merge sorted lists into a single sorted list

arrays - Yii2 数组排序

algorithm - 计算立方体的横截面

javascript - 从 React 到 PHP 文件的 Ajax 调用

php - TCPDF UTF-8。 INR 符号不显示

有人可以给我一个 "pure pointer notation"到 C 数组的例子吗?

javascript - 在数组中递增单击 Redux 函数