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
  )
)

コストが最も低いものから最も高いものの順に並べたいのですが、配列の最初の要素の[name]は「product_3」である必要があります。

4

1 に答える 1

4

To do this, you can't rely on sorting alone. You'd need a bit more logic:

  1. Capture the soon-to-be first element in its own variable.
  2. Remove that element from the array.
  3. Sort the array using usort().
  4. Shift the element from #1 to the front of the array with array_unshift().

So, for #1, you can do a bunch of things. The simplest is to loop the array to find the key that indexes where the first object is, and unset() it:

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

Now you have the first element in $first, so you have to sort the array with 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
});

Finally, add the first element back to the beginning of the now-sorted array:

array_unshift( $array, $first);

Disclaimer: None of the above implementation was tested.

于 2012-08-08T16:20:16.433 に答える