Search code examples
phparrayssorting

Synchronously sort an array by sorting another other array


Ive got 2 arrays, first one contains values of objects, and second one contains their IDs.
In this form:

$values[0] applies to $ids[0]
$values[1] applies to $ids[1]

I need to sort first array (using sort() ) from lowest to highest (values are ints) - That's not problem. Problem is, that When I sort array with values, I will lost ID of that value.
My question is: How to make that

If $values[0] turns to $values[5], automatically turn $ids[0] to $ids[5]


Thanks


Update:
Content of $values and $ids:

$values[0] = 1.5;
$values[1] = 2.4;
$values[2] = 15.7;
$values[3] = 11.7;
$values[4] = 4.8;
$values[5] = 0.4;

$ids[0] = 1;
$ids[1] = 2;
$ids[2] = 3;
$ids[3] = 4;
$ids[4] = 5;
$ids[5] = 6;

Solution

  • Combine the arrays first, then sort by key:

    $newArr = array_combine($ids, $values);
    ksort($newArr);