php - PHP 数组中的自定义排序 - 类似于 mysql ORDER BY FIELD(order_fied, 4, 1, 5, 2, 3)

标签 php mysql arrays sorting

<分区>

我有一个动态数组,例如包含以下元素:

$myArray = array(1, 2, 3, 4, 5);

我希望我的最终数组是:

$finalArray = array(4, 1, 5, [whaterever]);

进行既不升序也不降序或不遵循任何此类规则的自定义排序的最佳方法是什么?
感谢您的建议。

[编辑] 我已经编辑了我的问题。

最佳答案

你可以试试 usort功能。对于第二个参数,您应该编写一个函数来决定数组元素的放置方式。

是这样的:

<?php
$myArray = [1, 2, 3, 4, 5];

$properOrder = [4, 1, 5, 2, 3];
usort($myArray, function($a, $b) use($properOrder) {
    $index1 = array_search($a, $properOrder);
    $index2 = array_search($b, $properOrder);

    if ($index1 > $index2) {
        return 1;
    } else if ($index1 < $index2) {
        return -1;
    } else {
        return 0;
    }
});

print_r($myArray);

关于php - PHP 数组中的自定义排序 - 类似于 mysql ORDER BY FIELD(order_fied, 4, 1, 5, 2, 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35359383/

相关文章:

php - 是 $this->__invoke();在 PHP 中 100% 安全有效?

php - 可变的第 3 方 Paypal 购物车

php - 解构数组时避免 PHP 通知

php - 如何在mysql的WHERE子句中使用OR & AND

java - 从 Android 应用程序连接到 MySQL 服务器

c++ - 使用 clEnqueueWriteBuffer 的内存损坏 - OpenCL

php - 将平面数组中的每个字符串复制 N 次

php - 如何将 mysql 表导入 SOLR

arrays - 对 Swift 数组声明感到困惑

mysql - 从 MySQL 列获取字段长度