我有两个数组
$array1 = ["name1","name2","name3","name4"];
$array2 = ["name2","name1","name3","name4"];
我想知道的是阵列之间的位置变化。在上面的例子中,输出将是:
$returnArray = [
"name2"=>"up",
"name1"=>"down",
"name3"=>"same",
"name4"=>"same"
];
up =向上移动
down =向下移动
相同 =保持在同一位置
比较两个阵列确定位置变化的最快方法是什么?
答案 0 :(得分:0)
这应该适合你:
只需循环浏览$array1
的所有唯一值,然后查看array_search()
如果值处于相同位置,则向下或向上。
<?php
$array1 = ["name1","name2","name3","name4"];
$array2 = ["name2","name1","name3","name4"];
$result = [];
foreach(array_unique($array1) as $k => $v){
$result[$v] = $k == array_search($v, $array2) ? "same" : ($k < array_search($v, $array2) ? "up": "down");
}
print_r($result);
?>
在PHP 7中,只需使用太空船运营商,例如
<?php
$array1 = ["name1","name2","name3","name4"];
$array2 = ["name2","name1","name3","name4"];
$arr = ["-1" => "down", "0" => "same", "1" => "up"];
$result = [];
foreach(array_unique($array1) as $k => $v){
$result[$v] = $arr[array_search($v, $array2) <=> $k];
}
print_r($result);
?>