0

说我有一个对象数组:

Array (
  [0] => stdClass Object (
    [id] => 1
    [name] => product_1
    [cost] =>9.99
  )
  [1] => stdClass Object (
    [id] => 2
    [name] => product_2
    [cost] =>2.99
  )
  [2] => stdClass Object (
    [id] => 3
    [name] => product_3
    [cost] =>4.99
  )
  [3] => stdClass Object (
    [id] => 4
    [name] => product_4
    [cost] =>1.99
  )
  [4] => stdClass Object (
    [id] => 5
    [name] => product_5
    [cost] =>0.99
  )
)

我想从最低成本到最高成本对它们进行排序,但是数组中的第一个元素必须具有“product_3”的 [name]。

4

1 回答 1

4

为此,您不能仅依靠排序。你需要更多的逻辑:

  1. 在自己的变量中捕获即将成为第一个元素。
  2. 从数组中删除该元素。
  3. 使用 对数组进行排序usort()
  4. 使用 将元素从 #1 移动到数组的前面array_unshift()

所以,对于#1,你可以做很多事情。最简单的方法是循环数组以找到索引第一个对象所在的键,unset()它:

$first = null;
foreach( $array as $key => $obj) {
    if( $obj->name == 'product_3') {
        $first = $obj;
        unset( $array[ $key ]); 
        break;
    }
}

现在您有了 in 中的第一个元素$first,因此您必须使用以下命令对数组进行排序usort()

usort( $array, function( $a, $b) {  
    if( $a->cost == $b->cost) 
        return 0; 
    return $a->cost < $b->cost ? 1 : -1; // Might need to switch 1 and -1
});

最后,将第一个元素添加回已排序数组的开头:

array_unshift( $array, $first);

免责声明:上述实现均未经过测试。

于 2012-08-08T16:20:16.433 回答