Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP排序数组';比如';另一个数组。怎么用?_Php - Fatal编程技术网

PHP排序数组';比如';另一个数组。怎么用?

PHP排序数组';比如';另一个数组。怎么用?,php,Php,例如: $a = [ 'b', 'd', 'a', 'e' ] $b = [ 'e', 'a', 'q', 'b' ] 我想要 $b = [ 'b', 'a', 'e', 'q'] 我需要对$b进行排序,以使$a中已存在的每个元素的顺序与$a中元素的顺序相同 所以'b','a'和'e'在$a中,所以它们排在第一位,然后新的'q'排在最后 我问的是一个我不知道的函数,如果存在,或者是一种实现它的技术。只要每个数组都有不同的值,并且没有字符串键,这应该可以工作 $b = array_merge(

例如:

$a = [ 'b', 'd', 'a', 'e' ]
$b = [ 'e', 'a', 'q', 'b' ]
我想要

$b = [ 'b', 'a', 'e', 'q']
我需要对
$b
进行排序,以使
$a
中已存在的每个元素的顺序与
$a
中元素的顺序相同

所以
'b'
'a'
'e'
$a
中,所以它们排在第一位,然后新的
'q'
排在最后


我问的是一个我不知道的函数,如果存在,或者是一种实现它的技术。

只要每个数组都有不同的值,并且没有字符串键,这应该可以工作

$b = array_merge(array_intersect($a, $b), array_diff($b, $a));

这确实依赖于未记录的行为
array_diff

如果您想要一段很长、很麻烦的代码,它与Don't Panic非常有创意的oneliner做的事情相同,您可以使用我的。;-)

这种方法的优点是,它不依赖于函数的实现细节,如
array\u diff
。此外,它还为您提供了一个使用闭包的好机会,闭包除了非常酷之外没有什么特别的优势。代码可能会稍微短一点,但这种逐步解决方案至少应该相对容易理解

<?php
$a = [ 'b', 'd', 'a', 'e', 'x' ];
$b = [ 'e', 'a', 'q', 'b', 'g' ];

// Custom sorter functions like usort use a callback that compares items.
// The compare function should return < 0 if the first item should come 
// before the second, > 0 if the second item should come first, or 0
// if both items can be considered equal.
$sortFunction = function($i1, $i2) use ($a, $b)
{
  // Get the indexes of both item in array $a 
  $x1 = array_search($i1, $a);
  $x2 = array_search($i2, $a);
  // If both indexes are assigned, compare them.
  if ($x1 !== false && $x2 !== false)
    return $x1 - $x2;
  // Only the first item exists, so that one is 'smaller' (should come before the other)
  if ($x1 !== false)
    return -1;
  // Only the second item exists, so that one is 'smaller'
  if ($x2 !== false)
    return 1;
  // Neither exist. Keep the original order as they were in $b.
  return array_search($i1, $b) - array_search($i2, $b);
};

$c = $b;
usort($c, $sortFunction);

这个问题根本没有显示任何研究成果。他问的是。b,a,e,q与b,d,a,e的“顺序”如何相同?你能更清楚地定义规则吗?好的,这是一个很好的答案。我真的需要对键进行排序,但一旦我得到了正确的键顺序,使用两个循环,我会将每个值绑定到正确的键上。谢谢你,我会努力找到的,但是你怎么能保证这一切都会成功呢?我认为文档中没有指定排序顺序,您也不想依赖一些未记录的实现细节。@GolezTrol说得好。根据我在PHP源代码中看到的情况,它应该在我所述的条件下工作,但是我使用的三个函数的文档并不完全清楚。对于
array\u intersect
它确实声明保留键,对于
array\u merge
它说“带有数字键的输入数组中的值将在结果数组中用从零开始递增的键重新编号。”但是
array\u diff
文档中没有提到要保留的键,或者结果是否按特定顺序排列。