php - 基于其他数组排序数组

标签 php arrays

我有一个逗号分隔的字符串/数组:

$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,就像上面的示例一样。否则它会做相反的事情,这不是你想要的。

更多信息:http://php.net/manual/en/function.array-intersect.php

关于php - 基于其他数组排序数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40250223/

相关文章:

php - 在 PHP 中创建数组的简单方法

javascript - d3 转换为对象数组中的数字

c - 为什么我收到预期标识符或 '(' ?

javascript - 如何从数组创建数组

javascript - Zillow Data - json_encode 不工作 - 适用于常规变量

php - 模块 pcntl 已在第 0 行的未知中加载 - Apache x Cli

php - 检查数据库数组中是否存在值不起作用

Javascript 数组 - arr[arr.indexOf()] 的替代方案?

php - 2.3 中的相同代码不适用于 Magento 2.3.3 版本

php - 如何上传打开和阅读大型 (20 mb) csv 文件?