我有一个非常简单的数组:
array(
1 => 'asdf.php',
2 => 'jkl.php',
3 => 'qwer.php',
4 => 'ty.php',
5 => 'edit.php?param=my_val_a',
6 => 'edit.php?param=my_val_g',
7 => 'edit.php?param=my_val_i',
8 => 'zxcv.php',
9 => 'oiu.php',
10 => 'edit.php?param=my_val_w',
11 => 'bnm.php',
12 => 'hgb.php',
13 => 'edit.php?param=my_val_p'
)
我的目标是尝试保留数组的相同顺序,除了我希望所有带有字符串“?param = my_val”的项目彼此相邻,同时保留它们的顺序。所以最终的结果是:
array(
1 => 'asdf.php',
2 => 'jkl.php',
3 => 'qwer.php',
4 => 'ty.php',
5 => 'edit.php?param=my_val_a',
6 => 'edit.php?param=my_val_g',
7 => 'edit.php?param=my_val_i',
8 => 'edit.php?param=my_val_w',
9 => 'edit.php?param=my_val_p'
10 => 'zxcv.php',
11 => 'oiu.php',
12 => 'bnm.php',
13 => 'hgb.php',
)
我一直在玩usort()并且我已经能够将它们全部组合在一起,但保持相同的基本顺序让我挣扎。我该怎么做呢?
答案 0 :(得分:1)
这个怎么样(假设你的东西在$arr
中):
$parts_with_param = array();
$parts_with_no_param = array();
foreach ($arr as $val) {
if (strpos($val, '?param=my_val') !== false) {
$parts_with_param[] = $val;
} else {
$parts_with_no_param[] = $val;
}
}
// merge into a new variable or overwrite $arr if you like
$new_arr = array_merge($parts_with_param, $parts_with_no_param);