php-根据第二个给定数组对数组进行排序 [英] php - sort an array according to second given array

查看:93
本文介绍了php-根据第二个给定数组对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$a = array('val1','val2',200, 179,230, 234, 242); 
$b = array(230, 234, 242, 179, 100);

因此,数组$ a应该根据数组$ b排序,而$ resultArray应该是('val1' ,'val2',200,230,234,242,179)

So array $a should be sorted according to array $b and $resultArray should be ('val1','val2',200, 230, 234, 242, 179)

推荐答案

您的排序要求:


  1. 在排序数组中找不到的值先于找到的值。

  2. 然后:

  1. values not found in the sorting array come before values that ARE found.
  2. then:

  1. 按其在排序数组中的位置对找到的值进行排序

  2. 在排序数组中未找到的值通常/升序


翻转订单查找数组将提高效率,同时在进行键搜索之前要比在php中进行值搜索更快。

Flipping your order lookup array will permit improved efficiency while processing before key searching is faster than value searching in php.

代码:(演示

$array = ['val1', 'val2', 200, 179, 230, 234, 242]; 
$order = [230, 234, 242, 179, 100];
$keyedOrder = array_flip($order); // for efficiency

usort($array, function($a, $b) use ($keyedOrder) {
    return [$keyedOrder[$a] ?? -1, $a]
           <=>
           [$keyedOrder[$b] ?? -1, $b];
});
var_export($array);

输出:

array (
  0 => 'val1',
  1 => 'val2',
  2 => 200,
  3 => 230,
  4 => 234,
  5 => 242,
  6 => 179,
)

$ keyedOrder [$ variable]? -1 有效表示如果在查找中找不到该值,请使用 -1 将该项定位在查找数组中最小值之前( 0 )。如果在查找中找到该值作为键,则使用在查找中分配给该键的整数值。

$keyedOrder[$variable] ?? -1 effectively means if the value is not found in the lookup, use -1 to position the item before the lowest value in the lookup array (0). If the value IS found as a key in the lookup, then use the integer value assigned to that key in the lookup.

从PHP7.4开始,箭头函数语法可用于使代码段更加简洁,并避免使用 use()声明。

From PHP7.4, arrow function syntax can be used to make the snippet more concise and avoid the use() declaration.

演示

usort($array, fn($a, $b) => [$keyedOrder[$a] ?? -1, $a] <=> [$keyedOrder[$b] ?? -1, $b]);

这篇关于php-根据第二个给定数组对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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