按自定义顺序对数组的 php 数组进行排序


Sorting a php array of arrays by custom order

我有一个数组数组:

Array ( 
    [0] => Array (
        [id] = 7867867,
        [title] = 'Some Title'),
    [1] => Array (
        [id] = 3452342,
        [title] = 'Some Title'),
    [2] => Array (
        [id] = 1231233,
        [title] = 'Some Title'),
    [3] => Array (
        [id] = 5867867,
        [title] = 'Some Title')
)

需要按特定顺序进行:

  1. 3452342
  2. 5867867
  3. 7867867
  4. 1231233

我该怎么做呢?我以前对数组进行过排序,并阅读了许多其他关于它的文章,但它们总是基于比较的(即 valueA <valueB)。>

感谢帮助。

您可以使用

usort()来精确地指示数组的排序方式。在这种情况下,可以在比较函数中使用$order数组。

下面的示例使用closure使生活更轻松。

$order = array(3452342, 5867867, 7867867, 1231233);
$array = array(
    array('id' => 7867867, 'title' => 'Some Title'),
    array('id' => 3452342, 'title' => 'Some Title'),
    array('id' => 1231233, 'title' => 'Some Title'),
    array('id' => 5867867, 'title' => 'Some Title'),
);
usort($array, function ($a, $b) use ($order) {
    $pos_a = array_search($a['id'], $order);
    $pos_b = array_search($b['id'], $order);
    return $pos_a - $pos_b;
});
var_dump($array);

这项工作的关键是让正在比较的值是id$order数组中的位置。

比较

函数的工作原理是查找要在$order数组中比较的两个项目的 id 的位置。 如果$a['id']$order 数组中$b['id']之前,则函数的返回值将为负数($a较少,因此"浮动"到顶部)。如果$a['id']$b['id']之后,则函数返回一个正数($a更大,因此"下沉")。

最后,使用闭包没有特殊的原因;这只是我快速编写这些一次性函数的首选方法。 它同样可以使用普通的命名函数。

扩展 salathe对此额外要求的回答:

现在,当我将项目添加到数组而不是排序时会发生什么? 我不在乎它们出现的顺序是什么,只要它出现在那些之后我确实指定了。

您需要在排序功能中添加两个附加条件:

    "
  1. 不在乎"项目必须被视为大于"自定义"项目
  2. 两个"不在乎"项目必须被视为相等(您可以为这种情况添加决胜条件)

因此,修订后的代码将是:

$order = array(
    3452342,
    5867867,
    7867867,
    1231233
);
$array = array(
    array("id" => 7867867, "title" => "Must Be #3"),
    array("id" => 3452342, "title" => "Must Be #1"),
    array("id" => 1231233, "title" => "Must Be #4"),
    array("id" => 5867867, "title" => "Must Be #2"),
    array("id" => 1111111, "title" => "Dont Care #1"),
    array("id" => 2222222, "title" => "Dont Care #2"),
    array("id" => 3333333, "title" => "Dont Care #3"),
    array("id" => 4444444, "title" => "Dont Care #4")
);
shuffle($array);  // for testing
var_dump($array); // before
usort($array, function ($a, $b) use ($order) {
    $a = array_search($a["id"], $order);
    $b = array_search($b["id"], $order);
    if ($a === false && $b === false) { // both items are dont cares
        return 0;                       // a == b (or add tie-breaker condition)
    } elseif ($a === false) {           // $a is a dont care
        return 1;                       // $a > $b
    } elseif ($b === false) {           // $b is a dont care
        return -1;                      // $a < $b
    } else {
        return $a - $b;                 // sort $a and $b ascending
    }
});
var_dump($array); // after

输出:

Before                         |  After
-------------------------------+-------------------------------
array(8) {                     |  array(8) {
  [0]=>                        |    [0]=>
  array(2) {                   |    array(2) {
    ["id"]=>                   |      ["id"]=>
    int(4444444)               |      int(3452342)
    ["title"]=>                |      ["title"]=>
    string(12) "Dont Care #4"  |      string(10) "Must Be #1"
  }                            |    }
  [1]=>                        |    [1]=>
  array(2) {                   |    array(2) {
    ["id"]=>                   |      ["id"]=>
    int(3333333)               |      int(5867867)
    ["title"]=>                |      ["title"]=>
    string(12) "Dont Care #3"  |      string(10) "Must Be #2"
  }                            |    }
  [2]=>                        |    [2]=>
  array(2) {                   |    array(2) {
    ["id"]=>                   |      ["id"]=>
    int(1231233)               |      int(7867867)
    ["title"]=>                |      ["title"]=>
    string(10) "Must Be #4"    |      string(10) "Must Be #3"
  }                            |    }
  [3]=>                        |    [3]=>
  array(2) {                   |    array(2) {
    ["id"]=>                   |      ["id"]=>
    int(1111111)               |      int(1231233)
    ["title"]=>                |      ["title"]=>
    string(12) "Dont Care #1"  |      string(10) "Must Be #4"
  }                            |    }
  [4]=>                        |    [4]=>
  array(2) {                   |    array(2) {
    ["id"]=>                   |      ["id"]=>
    int(5867867)               |      int(2222222)
    ["title"]=>                |      ["title"]=>
    string(10) "Must Be #2"    |      string(12) "Dont Care #2"
  }                            |    }
  [5]=>                        |    [5]=>
  array(2) {                   |    array(2) {
    ["id"]=>                   |      ["id"]=>
    int(2222222)               |      int(1111111)
    ["title"]=>                |      ["title"]=>
    string(12) "Dont Care #2"  |      string(12) "Dont Care #1"
  }                            |    }
  [6]=>                        |    [6]=>
  array(2) {                   |    array(2) {
    ["id"]=>                   |      ["id"]=>
    int(3452342)               |      int(3333333)
    ["title"]=>                |      ["title"]=>
    string(10) "Must Be #1"    |      string(12) "Dont Care #3"
  }                            |    }
  [7]=>                        |    [7]=>
  array(2) {                   |    array(2) {
    ["id"]=>                   |      ["id"]=>
    int(7867867)               |      int(4444444)
    ["title"]=>                |      ["title"]=>
    string(10) "Must Be #3"    |      string(12) "Dont Care #4"
  }                            |    }
}                              |  }

其他使用迭代调用array_search()的方法的答案效率不高。 通过重组/翻转"订单"查找数组,您可以完全省略所有array_search()调用 - 使您的任务更加高效和简短。 我将使用最现代的"宇宙飞船操作员"(<=>),但早期的技术对于比较线也同样有效。 "空合并运算符"(??)将检查查找数组中给定id值是否存在,其方式与isset()相同 - 这总是比array_search()in_array()更有效。

代码:(演示)(使用 7.4 箭头函数语法的演示)(低于 PHP7 的演示)

// restructure with values as keys, and keys as order (ASC)
$order = array_flip([3452342, 5867867, 7867867, 1231233]);
// generating $order = [3452342 => 0, 5867867 => 1, 7867867 => 2, 1231233 => 3];
$default = count($order);
// generating $default = 4

usort($array, function($a, $b) use($order, $default) {
    return ($order[$a['id']] ?? $default) <=> ($order[$b['id']] ?? $default);
});
var_export($array);

更高效的解决方案

$dict = array_flip($order);
$positions = array_map(function ($elem) use ($dict) { return $dict[$elem['id']] ?? INF; }, $array);
array_multisort($positions, $array);

不要在每次比较中重新计算位置

当数组很大或获取 id 的成本更高时,使用 usort() 可能会变坏,因为您为每个比较重新计算 id。尝试使用预先计算的位置进行array_multisort()(请参阅以下示例中的mediumsortfastsort),这并不复杂。

此外,在每个比较的顺序数组中搜索 id(如在接受的答案中)不会提高性能,因为每次比较都会迭代它。计算一次。

在下面的代码片段中,您可以看到主要的三个排序函数:


  • slowsort接受的答案。搜索每个比较的位置。

  • mediumsort通过提前计算仓位提高slowsort

  • fastsort通过避免搜索所有内容来提高mediumsort

请注意,这些通过提供回退值 INF 来处理 id 未按顺序给出的元素。如果您的订单数组与原始数组的 ID 一对一匹配,那么请避免全部排序,只需将元素插入正确的位置即可。我添加了一个函数cheatsort正是这样做的。

您可以更普遍地按权重对数组进行排序(请参阅示例中的weightedsort)。确保只计算一次重量,以达到良好的性能。

性能(对于长度为 1000 的数组)

fastsort     about  1 ms
mediumsort   about  3 ms
slowsort     about 60 ms

提示:对于较大的阵列,差异会变得更糟。

排序功能比较

<?php
/**
 * accepted answer
 *
 * re-evaluate position in order on each comparison
 */
function slowsort(&$array, $order, $key = 'id')
{
  usort($array, function ($a, $b) use ($order, $key) {
    $pos_a = array_search($a[$key], $order);
    $pos_b = array_search($b[$key], $order);
    return $pos_a - $pos_b;
  });
}
/**
 * calculate element positions once
 */
function mediumsort(&$array, $order, $key = 'id')
{
  $positions = array_map(function ($elem) use ($order, $key) {
    return array_search($elem[$key], $order);
  }, $array);
  array_multisort($positions, $array);
}
/**
 * calculate positions without searching
 */
function fastsort(&$array, $order, $key = 'id')
{
  $dict = array_flip($order);
  $positions = array_map(function ($elem) use ($dict, $key) {
    return $dict[$elem[$key]] ?? INF;
  }, $array);
  array_multisort($positions, $array);
}
/**
 * when each order element gets used exactly once, insert elements directly
 */
function cheatsort(&$array, $order, $key = 'id')
{
  $dict = array_flip($order);
  $copy = $array;
  foreach ($copy as $elem) {
    $pos = $dict[$elem[$key]];
    $array[$pos] = $elem;
  }
}
/**
 * Sort elements in $array by their weight given by $weight_func
 * 
 * You could rewrite fastsort and mediumsort by replacing $position by a weight function
 */
function weightedsort(&$array, $weight_func)
{
  $weights = array_map($weight_func, $array);
  array_multisort($weights, $array);
}

/**
 * MEASUREMENTS
 */
/**
 * Generate the sorting problem
 */
function generate($size = 1000)
{
  $order = array();
  $array = array();
  for ($i = 0; $i < $size; $i++) {
    $id = random_int(0, PHP_INT_MAX);
    $order[] = $id;
    $array[] = array('id' => $id);
  }
  shuffle($order);
  return [$array, $order];
}
/**
 * Time $callable in ms
 */
function time_it($callable)
{
  $then = microtime(true);
  $callable();
  $now = microtime(true);
  return 1000 * ($now - $then);
}
/**
 * Time a sort function with name $sort_func
 */
function time_sort($sort_func) 
{
  echo "Timing $sort_func", PHP_EOL;
  [$array, $order] = generate();
  echo time_it(function () use ($sort_func, &$array, $order) {
    $sort_func($array, $order);
  }) . ' ms' . PHP_EOL;
}
time_sort('cheatsort');
time_sort('fastsort');
time_sort('mediumsort');
time_sort('slowsort');

没有排序,你也可以得到它。

  1. 如果没有重复的 id 并且 $order 包含 $array 中的所有id值,并且 $array 中的id列包含 $order 中的所有值,则可以通过将值翻转为$order中的键来实现相同的结果,然后将临时的第一级键分配给数组,然后将$array合并或替换到 $order 中。

    $order = array(3452342, 5867867, 7867867, 1231233);
    $array = array(
        array('id' => 7867867, 'title' => 'Some Title'),
        array('id' => 3452342, 'title' => 'Some Title'),
        array('id' => 1231233, 'title' => 'Some Title'),
        array('id' => 5867867, 'title' => 'Some Title'),
    );
    $order = array_flip($order);
    $array = array_column($array,null,"id");
    $result = array_replace($order,$array);
    var_dump(array_values($result));
    
  2. $array中可能存在重复的 id:

    $order = array(3452342, 5867867, 7867867, 1231233);
    $array = array(
        array('id' => 7867867, 'title' => 'Some Title'),
        array('id' => 3452342, 'title' => 'Some Title'),
        array('id' => 1231233, 'title' => 'Some Title'),
        array('id' => 5867867, 'title' => 'Some Title'),
    );
    $order_dict = array_flip($order);
    $order_dict = array_combine($order, array_fill(0, count($order), []));
    foreach($array as $item){
        $order_dict[$item["id"]][] = $item;
    }
    //$order_dict = array_filter($order_dict);  // if there is empty item on some id in $order array
    $result = [];
    foreach($order_dict as $items){
        foreach($items as $item){
            $result[] = $item;
        }
    }
    var_dump($result);
    

@salathe 对于那些很难理解 salathe's usort 在做什么的人:

$array中的每个项目都是锦标赛中的"冠军",位于新数组的开头(除了不是第一,而是希望成为第 0 名)。

$a是主场冠军,$b比赛中的对手冠军。

回调中的 $pos_a 和 $pos_b 是争夺冠军 A 和 B 时将使用的属性。在本例中,此属性是 $order 中冠军 id 的索引。

然后是回归时的战斗。现在我们看看拥有更多或更少的属性是否更好。在一场Usort战斗中,主场冠军想要一个负数,这样他就可以更快地进入阵列。客队冠军想要一个正数。如果有0,那就是平局。

因此,按照这个类比,当从主队属性中减去客队冠军属性($order 中的索引)时,客队冠军属性越大,通过获得正数获胜的可能性就越小。但是,如果您要颠倒属性的使用方式,现在主队冠军的属性将从客队冠军的属性中减去。在这种情况下,客队冠军的较大数字更有可能使他以正数结束比赛。

代码如下所示:

注意:代码运行了很多次,就像真正的锦标赛有很多战斗一样,以决定谁先得到(即 0/数组开始)

//tournament with goal to be first in array
    usort($champions, function ($home, $away) use ($order) {
        $home_attribute = array_search($a['id'], $order);
        $away_attribute = array_search($b['id'], $order);
        //fight with desired outcome for home being negative and away desiring positive
        return $home_attribute - $away_attribute;
    });
如果要

维护索引关联,则需要定义自己的比较函数并使用usortuasort

我遇到了同样的问题,@mickmackusa有我需要的答案。当存在NULL值时,所选答案不会排序。例如:

$order = array(3, 2, 10);
$array = array(
    array('id' => NULL, 'title' => 'any order since null but not top'),
    array('id' => NULL, 'title' => 'any order since null but not top'),
    array('id' => NULL, 'title' => 'any order since null but not top'),
    array('id' => 2, 'title' => 'should be top'),
);
usort($array, function ($a, $b) use ($order) {
    $pos_a = array_search($a['id'], $order);
    $pos_b = array_search($b['id'], $order);
    return $pos_a - $pos_b;
});

上面的结果将显示以下输出:

array(4) {
  [0]=>
  array(2) {
    ["id"]=>
    NULL
    ["title"]=>
    string(32) "any order since null but not top"
  }
  [1]=>
  array(2) {
    ["id"]=>
    NULL
    ["title"]=>
    string(32) "any order since null but not top"
  }
  [2]=>
  array(2) {
    ["id"]=>
    NULL
    ["title"]=>
    string(32) "any order since null but not top"
  }
  [3]=>
  array(2) {
    ["id"]=>
    int(2)
    ["title"]=>
    string(13) "should be top"
  }
}

在@mickmackusa的答案中,它不仅消除了排序中的空值,而且还将订单基础中可用的任何内容放在第一位。因此,由于在数组中唯一可用的是 2,因此它将位于顶部。

虽然它在 PHP 5.6 中不起作用。所以我把它转换为兼容 PHP 5.6。这就是我得到的

usort($array, function($a, $b) use($order, $default) {
    $a = (isset($order[$a['id']]) ? $order[$a['id']] : $default);
    $b = (isset($order[$b['id']]) ? $order[$b['id']] : $default);
    if($a == $b) return 0;
    elseif($a > $b) return 1;
    return -1;
});

上述排序的结果将是

array(4) {
  [0]=>
  array(2) {
    ["id"]=>
    int(2)
    ["title"]=>
    string(13) "should be top"
  }
  [1]=>
  array(2) {
    ["id"]=>
    NULL
    ["title"]=>
    string(32) "any order since null but not top"
  }
  [2]=>
  array(2) {
    ["id"]=>
    NULL
    ["title"]=>
    string(32) "any order since null but not top"
  }
  [3]=>
  array(2) {
    ["id"]=>
    NULL
    ["title"]=>
    string(32) "any order since null but not top"
  }
}

我希望我的代码转换能够帮助在具有较低 php 版本的过时服务器上工作的开发人员。