-1

I have a multidimensional array like this.

arr[4]=array('name' => 'ab', 'aid' => 1 'qty' => 10);
arr[5]=array('name' => 'ac', 'aid' => 3 'qty' => 15);
arr[3]=array('name' => 'ad', 'aid' => 2 'qty' => 100);
arr[2]=array('name' => 'ae', 'aid' => 2 'qty' => 150);

and I need to sort them by the 'aid' but don't change the main index like this.

arr[4]=array('name' => 'ab', 'aid' => 1 'qty' => 10);
arr[2]=array('name' => 'ae', 'aid' => 2 'qty' => 150);
arr[3]=array('name' => 'ad', 'aid' => 2 'qty' => 100);
arr[5]=array('name' => 'ac', 'aid' => 3 'qty' => 15);

is that possible? what should I do? thanks.

wildashfihana
  • 311
  • 1
  • 2
  • 9
  • WHat's your php version? – Mojtaba Aug 16 '16 at 19:06
  • If you are using php5.5 or higher, you can use http://php.net/manual/en/function.array-column.php . By the way, this is your answer: http://stackoverflow.com/questions/16306416/sort-php-multi-dimensional-array-based-on-key – Mojtaba Aug 16 '16 at 19:10

1 Answers1

0

From PHP manual

<?php
    $data[] = array('volume' => 67, 'edition' => 2);
    $data[] = array('volume' => 86, 'edition' => 1);
    $data[] = array('volume' => 85, 'edition' => 6);
    $data[] = array('volume' => 98, 'edition' => 2);
    $data[] = array('volume' => 86, 'edition' => 6);
    $data[] = array('volume' => 67, 'edition' => 7);
?>

In this example, we will order by volume descending, edition ascending.

We have an array of rows, but array_multisort() requires an array of columns, so we use the below code to obtain the columns, then perform the sorting.

<?php
    // Obtain a list of columns
    foreach ($data as $key => $row) {
        $volume[$key]  = $row['volume'];
        $edition[$key] = $row['edition'];
    }

    // Sort the data with volume descending, edition ascending
    // Add $data as the last parameter, to sort by the common key
    array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
?>

http://php.net/manual/en/function.array-multisort.php

Edit

For your need you requested:

$arr[4]=array('name' => 'ab', 'aid' => 1, 'qty' => 10);
$arr[5]=array('name' => 'ac', 'aid' => 3, 'qty' => 15);
$arr[3]=array('name' => 'ad', 'aid' => 2, 'qty' => 100);
$arr[2]=array('name' => 'ae', 'aid' => 2, 'qty' => 150);

$keyPositions = array();
foreach ($arr as $key => $value) {
    $keyPositions[] = $key;
}


foreach ($arr as $key => $row) {
    $aid[$key]  = $row['aid'];
}

array_multisort($aid, SORT_ASC, $arr);

$sortedArray = array();
foreach ($arr as $key => $value) {
    $sortedArray[$keyPositions[$key]] = $value;
}

echo '<pre>';
print_r($sortedArray);
echo '</pre>';

?>
eeXBee
  • 133
  • 7