我有一个逗号分隔的字符串/数组:
$input = "facebook,steam,tumblr,email,instagram,twitter,twitch,youtube,pinterest,amazon,disqus";
$input = explode(",", $input);
我想根据另一个数组进行排序:
$order = "email,facebook,instagram,twitter,twitch,youtube,steam,pinterest,tumblr,amazon,disqus";
$order = explode(",", $order);
$input
将始终包含 $order
中的值,我希望它根据它在 $order< 中的顺序进行排序
。这有点棘手,因为 $input
将仅包含来自 $order
的值的子集。
例如,输入 twitter,twitch,email,facebook
将返回 email,facebook,twitter,twitch
我已经找到This Solution但它不适用,因为我没有处理数组中的键。
最佳答案
不需要做任何花哨的排序算法。你可以这样做:
array_intersect($order, $input);
这将返回一个数组,其中包含 $input
中存在的 $order
的所有值。值得庆幸的是,此函数在 $order
中保留了原始顺序。
注意:array_intersect()
的参数顺序很重要。确保首先传入 $order
,因为那是你的引用数组,然后传入 $input
,就像上面的示例一样。否则它会做相反的事情,这不是你想要的。
关于php - 基于其他数组排序数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40250223/