我需要按特定的顺序对数组进行排序,按键进行排序。我知道我需要做一些像下面这样的事情,但是尝试了很多不同的方法,但无法得到我想要的结果。
有人能帮忙吗?
数组的一个例子如下所示,我正在寻找的结果是:连接性,连络中心,维修站,云,托管,业务连续性。
$solutions =数组(业务连续性=>业务连续性连接=>连接云和托管=>云托管联系中心=>联系人中心)
function reorder_solutions($a, $b){
$custom = array('Lines & Calls', 'Mobile', 'Connectivity', 'Wifi', 'LAN', 'UC&C', 'Contact Centres', 'Cloud & Hosting', 'Managed Services', 'Security', 'Business Continuity');
foreach ($custom as $k => $v){
if ($k == $b) {
return 0;
}
return ($k < $b) ? -1 : 1;
}
}
uasort($solutions, "reorder_solutions");发布于 2017-03-29 16:30:49
有一种方法可以做到:
// loop over the $custom array
foreach ($custom as $key) {
// add each key found in $solutions into a $sorted array
// (they'll be added in custom order)
if (isset($solutions[$key])) {
$sorted[$key] = $solutions[$key];
// remove the item from $solutions after adding it to $sorted
unset($solutions[$key]);
}
}
// merge the $sorted array with any remaining items in $solutions
$solutions = array_merge($sorted, $solutions);另一种方式是:
// create an array using the values of $custom as keys with all empty values
$custom = array_fill_keys($custom, null);
// merge that array with $solutions (same keys will be overwritten with values
// from $solutions, then remove the empty values with array_filter
$solutions = array_filter(array_merge($custom, $solutions));如果你愿意的话,你可以把它做成一条线。
$solutions = array_filter(array_merge(array_fill_keys($custom, null), $solutions));https://stackoverflow.com/questions/43098979
复制相似问题