简体   繁体   English

PHP 根据值列表对数组进行排序

[英]PHP Sorting an array based on list of values

I'm looking for an approach to sort an array of arrays.我正在寻找一种对 arrays 数组进行排序的方法。

Here is simplified example;这是简化的示例;

$myArray = [ 
  ['ref' => 103, 'refList' => '101,102,111'],
  ['ref' => 104, 'refList' => '101,103'],
  ['ref' => 105, 'refList' => '106,103'],
  ['ref' => 106, 'refList' => '103,104,110'],
];

The sorting rule for the array items is;数组项的排序规则是;

Items with references contained in the 'refList' must come after any items with the matching 'ref' 'refList' 中包含引用的项目必须在具有匹配 'ref' 的任何项目之后

So in this scenario the correct order would be;所以在这种情况下,正确的顺序是;

  ['ref' => 103, 'refList' => '101,102,111'],
  ['ref' => 104, 'refList' => '101,103'],
  ['ref' => 106, 'refList' => '103,104'],
  ['ref' => 105, 'refList' => '106,103,110'],

I've tried some very long winded approaches and also usort(), but can't get this right.我尝试了一些非常冗长的方法和 usort(),但无法做到这一点。 I went down the following route;我沿着以下路线走;

usort($myArray, 'refSorter');

function refSorter($a, $b) {

    $arrayOfRefs = explode(',', $b['refList']);

    if (in_array($a['ref'], $arrayOfRefs)) {
        return 1;
    }
    return 0;
}

You're missing one case in your comparison algorithm.您的比较算法中缺少一个案例。 You should return -1 when A ref is included in B refList and 1 when B ref is included in A refList.当 A ref 包含在 B refList 中时,您应该返回-1 ;当 B ref 包含在 A refList 中时,您应该返回1

$myArray = [ 
  ['ref' => 103, 'refList' => '101,102,111'],
  ['ref' => 104, 'refList' => '101,103'],
  ['ref' => 105, 'refList' => '106,103'],
  ['ref' => 106, 'refList' => '103,104,110'],
];

usort($myArray, 'refSorter');

function refSorter($a, $b) {
    $aRefs = explode(',', $a['refList']);
    $bRefs = explode(',', $b['refList']);

    if (in_array($a['ref'], $bRefs)) {
        return -1;
    }

    if (in_array($b['ref'], $aRefs)) {
        return 1;
    }

    return $a['ref'] <=> $b['ref'];
}

Result:结果:

ref => 103 | refList => 101,102,111
ref => 104 | refList => 101,103
ref => 106 | refList => 103,104,110
ref => 105 | refList => 106,103

PHPSandbox PHP沙盒

The sort rule is somewhat ambiguous, but how about this one (modify to match exact criteria):排序规则有点模棱两可,但是这个规则怎么样(修改以匹配确切的标准):

function refSorter($a, $b) {

    $arrayOfRefsa = explode(',', $a['refList']);
    $arrayOfRefsb = explode(',', $b['refList']);

    $refCmp =  $a['ref'] === $b['ref'] ? 0 : ($a['ref'] < $b['ref'] ? -1 : 1);
    $refListCmp = in_array($b['ref'], $arrayOfRefsa) ? 1 : (in_array($a['ref'], $arrayOfRefsb) ? -1 : 0);
    return $refListCmp*10+$refCmp;
}

Gives correct output for example list given (tested)给出正确的 output 例如给出的列表(测试)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM