user336502
user336502

Reputation:

Synchronously sort values in two particular rows of a 2d array according to the first nominated row

How do I sort both rows in this array by the nums values?

[
    'nums' => [34, 12, 13],
    'players' => ['Mike', 'Bob', 'Mary']
]

Desired result:

[
    'nums' => [12, 13, 34],
    'players' => ['Bob', 'Mary', 'Mike']
]

Upvotes: 2

Views: 99

Answers (2)

bcosca
bcosca

Reputation: 17555

array_multisort($x['nums'],$x['players']);

Upvotes: 1

Russell Dias
Russell Dias

Reputation: 73282

Try the sort function.

bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

This function sorts an array. Elements will be arranged from lowest to highest when this function has completed.

Also check out asort and arsort

EDIT

I did not take into account your Multidimensional array.

   <?php
    //code derived from comments on the php.net/sort page.
    // $sort used as variable function--can be natcasesort, for example
      function sort2d( &$arrIn, $index = null, $sort = 'sort') {
        // pseudo-secure--never allow user input into $sort
        if (strpos($sort, 'sort') === false) {$sort = 'sort';}
        $arrTemp = Array();
        $arrOut = Array();

        foreach ( $arrIn as $key=>$value ) {
          reset($value);
          $arrTemp[$key] = is_null($index) ? current($value) : $value[$index];
        }

        $sort($arrTemp);

        foreach ( $arrTemp as $key=>$value ) {
          $arrOut[$key] = $arrIn[$key];
        }

        $arrIn = $arrOut;
      }
    ?>

Upvotes: 1

Related Questions