在 JavaScript 中,可以根据字符串在每个元素中的位置对数组进行排序,使用如下内容:
arr = arr.sort(function (a, b) {
return a.indexOf(str) - b.indexOf(str);
});
可以对 PHP 数组做类似的事情,以便根据字符串在每个元素中的位置进行排序吗?
最佳答案
希望这对那些来的人有帮助。我建议对@DannyPhantom 答案进行改进。
任何不包含搜索字符串的值都将放在第一位。 strpos
当没有找到搜索到的字符串时返回 false
,因此需要处理,因为我们都(应该)知道,false == 0
当在开头找到搜索的字符串时,code> 和 strpos()
返回 0。
Warning
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
所以,这是我的解决方案
usort($arr, function($a, $b) use ($str) {
$idx_a = strpos($a, $str) === false ? PHP_INT_MAX : strpos($a, $str);
$idx_b = strpos($b, $str) === false ? PHP_INT_MAX : strpos($b, $str);
return $idx_a - $idx_b;
});
关于javascript - 如何根据字符串在每个元素中的位置对 PHP 数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32430541/