通过继续值对Usort排序多维数组
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通过继续值对Usort排序多维数组相关的知识,希望对你有一定的参考价值。
我有一个数组:
$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);
但它并没有按照描述的方式排序。有任何想法吗?
希望有一个更好的解决方案,但如果你排序的次数与数组中的元素一样多,并返回相等或更大,那么它的工作原理;即使你不知道开头或开头不是第一个元素。由于usort
遍历和比较的方式,返回相等或更少不起作用:
foreach($cards as $card) {
usort($cards, function ($a, $b) {
return ( $a["to"] === $b["from"] ) ? 0 : 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
这是一种方式。通过迭代找到开始并搜索路径:
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.
" ; break ; }
}
print_r($way);
以上是关于通过继续值对Usort排序多维数组的主要内容,如果未能解决你的问题,请参考以下文章