PHP - 基于另一个数组元素排序数组元素:) [英] PHP - Sort array elements based on another array's elements :)

查看:136
本文介绍了PHP - 基于另一个数组元素排序数组元素:)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有两个数组。其中之一是这样的(它的值或元素的数量可以改变):

so I have two arrays. one of them looks like this (it's values or the number of elements can change):

array('4dec' , 'def3', 'a3d6', 'd12f');

和其他

array(array('id' => 'd12f', 'name' => 'John'),
      array('id' => 'a5f1', 'name' => 'Kathy'),
      array('id' => 'def3', 'name' => 'Jane'),
      array('id' => 'a3d6', 'name' => 'Amy'),
      array('id' => '4dec', 'name' => 'Mary'),      
      array('id' => 'ecc2', 'name' => 'Fred'));

(这应该不会改变,元素和值是相同的,每次)。

(this one shouldn't change, elements and values are the same every time).

注意到第一个具有:第二个几个元素。
我怎样才能根据从一日一元素第2个数组排序?

notice the first one has a few elements from the 2nd one. How can I sort the 2nd array based on the elements from the 1st one?

所以基本上,在这种情况下,第2个数组应成为:

so basically, in this case the 2nd array should become:

array(array('id' => '4dec', 'name' => 'Mary'),
      array('id' => 'def3', 'name' => 'Jane'),
      array('id' => 'a3d6', 'name' => 'Amy'),
      array('id' => 'd12f', 'name' => 'John'),
      array('id' => 'a5f1', 'name' => 'Kathy'),
      array('id' => 'ecc2', 'name' => 'Fred'));

(即存在于第一个1的元件在顶部移动时,以相同的顺序为1,而其它的单独留)。

(the elements that exist in the 1st one are moved at the top, in the same order as the 1st, and the others are left alone).

推荐答案

稳定性是一个扭曲,因为PHP不尊重,任何更长的时间,但一些额外的工作保持了稳定的排序

Stability was a twist, as PHP doesn't respect that any longer, but a little extra work keeps the sort stable.

$order_by = array('4dec' , 'def3', 'a3d6', 'd12f');

$data = array(array('id' => 'd12f', 'name' => 'John'),
              array('id' => 'a5f1', 'name' => 'Kathy'),
              array('id' => 'def3', 'name' => 'Jane'),
              array('id' => 'a3d6', 'name' => 'Amy'),
              array('id' => '4dec', 'name' => 'Mary'),      
              array('id' => 'ecc2', 'name' => 'Fred'));

// create a lookup table for sorted order to avoid repeated searches
$order_index = array_flip($order_by);

// create a lookup table for original order: in PHP 4.1.0 usort became unstable
// http://www.php.net/manual/en/function.usort.php
$orig_order_by = array_map(function($a){return $a['id'];}, $data);
$orig_index = array_flip($orig_order_by);

// sort values by specified order, with stability
$compare = function($a, $b) use (&$order_index, &$orig_index) {
    $aid = $a['id'];
    $bid = $b['id'];

    $ai = $order_index[$aid];
    $bi = $order_index[$bid];

    if ($ai === null and $bi === null) { // original sort order for stability
        return $orig_index[$aid] - $orig_index[$bid];
    }
    if ($ai === null) { return 1; }
    if ($bi === null) { return -1; }

    return $ai - $bi;
};
usort($data, $compare);
var_dump($data);

这篇关于PHP - 基于另一个数组元素排序数组元素:)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆