如果满足特定条件,请将某些项目移动到数组的末尾


Move some items to the end of the array if they fulfill a specific condition

我有一个要排序的路径数组。。。

Array
(
    /something/foo1
    /something/special/foo2
    /something/foo3
    /something/special/foo4
    /something/foo5
    /something/special/foo6
)

使得所有包含CCD_ 1的路径都像这样结束在阵列的末尾:

Array
(
    /something/foo1
    /something/foo3
    /something/foo5
    /something/special/foo2
    /something/special/foo4
    /something/special/foo6
)

路径的原始排序顺序必须保持不变(因此1,2,3,4,5,6=>1,3,5,2,4,6)。有没有一种优雅的方法可以做到这一点?这可以通过使用usort函数来实现吗?

在您的特定示例中,您可以简单地使用asort($array);

但这是假设foo总是foo。

输出:

array(6) {
  [0]=>
  string(15) "/something/foo1"
  [2]=>
  string(15) "/something/foo3"
  [4]=>
  string(15) "/something/foo5"
  [1]=>
  string(23) "/something/special/foo2"
  [3]=>
  string(23) "/something/special/foo4"
  [5]=>
  string(23) "/something/special/foo6"
}

如果不是这样,请告诉我,我会做其他事情

这是新方法参考意见:

$array  = array(
    '/something/zoo',
    '/something/special/foo',
    '/something/loo',
    '/something/special/goo',
    '/something/boo',
    '/something/special/poo'
);
uasort($array, function($a, $b) {
    $specialInA = strpos($a, '/special/') !== false;
    $specialInB = strpos($b, '/special/') !== false;
    if ($specialInA > $specialInB) {
        return 1;
    }
    if ($specialInB > $specialInA) {
        return -1;
    }
    return $a > $b;
});

输出:

array(6) {
  [4]=>
  string(14) "/something/boo"
  [2]=>
  string(14) "/something/loo"
  [0]=>
  string(14) "/something/zoo"
  [1]=>
  string(22) "/something/special/foo"
  [3]=>
  string(22) "/something/special/goo"
  [5]=>
  string(22) "/something/special/poo"
}

可能可以写得更好,但应该可以使用

您可以使用unset并附加[],就像一样

$x = array(1,2,3);
$x[] = $x[1];
unset($x[1]);
print_r($x);
Array
(
    [0] => 1
    [2] => 3
    [3] => 2
)

因此,您可以在数组上循环,测试每个元素,并将包含该模式的元素翻转到最后。

$len = count($a);
for ($i=0; $i<$len; $i++) {
    if (...) {
        $a[] = $a[i];
        unset($a[i]);
    }
}

Edit:php的数组同时是列表、散列和数组。可以将元素移动到末尾,同时保留其索引!例如

$a = array(1,2,3);
$t = $a[1];
unset($a[1]);
$a[1] = $t;
print_r($a);
Array
(
    [0] => 1
    [2] => 3
    [1] => 2
)