0

I have an array of objects, each object has an index: object->index, which is a positive integer.

I have a second array, each entry is an index, corresponding uniquely to one of object->index. I want to sort the first array of objects so that they are in the same order as the order of the second arrays indexes.

Does that make sense?

Thanks.

1
  • so you have an array('1'=>object->index{=1}, '2'=>object->index{=2}), what's inside {} is the value of your index. And you have a second array with the same structure, and you want to sort one array to be the same order as the other? Commented May 11, 2012 at 14:40

3 Answers 3

1

I would flip your second array (array_flip) so that you can look up an object's desired position more easily. Then you can just iterate through your objects like so:

$indices = array_flip( $second_array );
$sorted_objects = array();
foreach ( $objects as $object ) {
  $sorted_objects[$indices[$object->index]] = $object;
}
Sign up to request clarification or add additional context in comments.

3 Comments

+1 Either that or use array_search(). Might also need to ksort($sorted_objects); afterward so it can be iterated in desired order.
Thanks! This worked. Wiseguy was also correct, a ksort was required afterwards.
@Hardworker, or you could do $sorted_objects = array_fill( 0, count( $objects ), NULL ); so that objects will be inserted at the proper position instead of appended (I thought that PHP would insert them in the correct order if the keys were numeric, but obviously it does not).
0
$objArray = ...;
$sortArray = ...;
$newArray = array(); // the sorted array

foreach( $sortArray as $index )
{
  foreach( $objArray as $obj )
  {
    if( $obj->index === $index )
    {
      $newArray[] = $obj;
      break;
    }
  }
}

like this?

Comments

0

Check out usort (http://au.php.net/manual/en/function.usort.php): this allows you to sort an array by specifying a function. That function would be to get the index of the object.

function cmp($obj1, $obj2) {

    if ($obj1->index == $obj2->index) {
        return 0;
    }
    return ($obj1->index < $obj2->index) ? -1 : 1;
}

usort($aObjects, "cmp");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.