通过继续值对Usort排序多维数组

问题描述 投票:4回答:3

我有一个数组:

$cards = [
    [
        "from" => "Barcelona",
        "to" => "Gerona Airport",        
    ],
    [
        "from" => "Stockholm",
        "to" => "New York JFK",          
    ],
    [
        "from" => "Gerona Airport",
        "to" => "Stockholm",          
    ],
    [
        "from" => "Madrid",
        "to" => "Barcelona",          
    ]
];

我需要对它进行排序以进行持续的旅行,其中from与之前的to匹配,或者如果不匹配则设置为开始,例如:

Array (
    [0] => Array ( [from] => Madrid [to] => Barcelona )  
    [1] => Array ( [from] => Barcelona [to] => Gerona Airport )
    [2] => Array ( [from] => Gerona Airport [to] => Stockholm ) 
    [3] => Array ( [from] => Stockholm [to] => New York JFK ) 
)

我想使用usort

usort($cards, function ($a, $b) {
          return ( $a["to"] === $b["from"] ) ? -1 : 1;
      });

print_r($cards);

但它并没有按照描述的方式排序。有任何想法吗?

php arrays multidimensional-array usort
3个回答
2
投票

希望有一个更好的解决方案,但如果你排序的次数与数组中的元素一样多,并返回相等或更大,那么它的工作原理;即使你不知道开头或开头不是第一个元素。由于usort遍历和比较的方式,返回相等或更少不起作用:

foreach($cards as $card) {
    usort($cards, function ($a, $b) {
                      return ( $a["to"] === $b["from"] ) ? 0 : 1;
                  });
}

它可以使用较少的迭代,但是将每个迭代与所有其他迭代相比似乎是安全的。


1
投票

您可以采用递归方法并指定要从哪个城市开始。

默认情况下,您从doSort($cards, $result);开始在马德里。

如果你想从“赫罗纳机场”继续旅行,你可以用qazxsw poi开始

doSort($cards, $result, "Gerona Airport");

$cards = [ [ "from" => "Barcelona", "to" => "Gerona Airport", ], [ "from" => "Stockholm", "to" => "New York JFK", ], [ "from" => "Gerona Airport", "to" => "Stockholm", ], [ "from" => "Madrid", "to" => "Barcelona", ] ]; $result = []; function doSort($cards, &$result, $start = "Madrid") { foreach ($cards as $key => $card) { if ($card["from"] === $start) { $result[] = $card; doSort($cards, $result, $card["to"]); } } } doSort($cards, $result); print_r($result);

那会给你:

Php output demo

0
投票

这是一种方式。通过迭代找到开始并搜索路径:

Array
(
    [0] => Array
        (
            [from] => Madrid
            [to] => Barcelona
        )

    [1] => Array
        (
            [from] => Barcelona
            [to] => Gerona Airport
        )

    [2] => Array
        (
            [from] => Gerona Airport
            [to] => Stockholm
        )

    [3] => Array
        (
            [from] => Stockholm
            [to] => New York JFK
        )

)

输出:

// 1. Find the start
$start = null;
$starts = array_column($cards,'from');
$ends = array_column($cards,'to');
foreach ($cards as $card) {
    if (!in_array($card['from'], $ends)) $start=$card;
}
// 2. Find way
$way=[$start];
while (count($cards)>1) {
    $found = false ;
    foreach ($cards as $k => $card) {
        if ($card['from'] == $start['to']) {
            $way[] = $card;
            $start = $card;
            unset($cards[$k]);
            $found = true ;
            break 1;
        }
    }
    if (!$found) { echo "Impossible to use all cards.\n" ; break ; }
}
print_r($way);
© www.soinside.com 2019 - 2024. All rights reserved.