1

我有一个非常简单的数组:

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() 并且我已经能够将它们放在一起,但是保持相同的基本顺序让我很挣扎。我该怎么做呢?

4

1 回答 1

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);
于 2013-04-02T02:50:56.827 回答