Change array order in php

arsort

Sorts array in place in descending order, such that its keys maintain their correlation with the values they are associated with.

This is used mainly when sorting associative arrays where the actual element order is significant.

Note:

If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined.

Note:

Resets array’s internal pointer to the first element.

Parameters

The optional second parameter flags may be used to modify the sorting behavior using these values:

  • SORT_REGULAR — compare items normally; the details are described in the comparison operators section
  • SORT_NUMERIC — compare items numerically
  • SORT_STRING — compare items as strings
  • SORT_LOCALE_STRING — compare items as strings, based on the current locale. It uses the locale, which can be changed using setlocale()
  • SORT_NATURAL — compare items as strings using «natural ordering» like natsort()
  • SORT_FLAG_CASE — can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively

Return Values

Always returns true .

Changelog

Version Description
8.2.0 The return type is true now; previously, it was bool .

Examples

Example #1 arsort() example

$fruits = array( «d» => «lemon» , «a» => «orange» , «b» => «banana» , «c» => «apple» );
arsort ( $fruits );
foreach ( $fruits as $key => $val ) echo » $key = $val \n» ;
>
?>

The above example will output:

a = orange d = lemon b = banana c = apple

The fruits have been sorted in reverse alphabetical order, and the index associated with each element has been maintained.

See Also

  • sort() — Sort an array in ascending order
  • asort() — Sort an array in ascending order and maintain index association
  • The comparison of array sorting functions

User Contributed Notes 6 notes

If you need to sort a multi-demension array, for example, an array such as

$TeamInfo[$TeamID][«WinRecord»]
$TeamInfo[$TeamID][«LossRecord»]
$TeamInfo[$TeamID][«TieRecord»]
$TeamInfo[$TeamID][«GoalDiff»]
$TeamInfo[$TeamID][«TeamPoints»]

and you have say, 100 teams here, and want to sort by «TeamPoints»:

first, create your multi-dimensional array. Now, create another, single dimension array populated with the scores from the first array, and with indexes of corresponding team_id. ie
$foo[25] = 14
$foo[47] = 42
or whatever.
Now, asort or arsort the second array.
Since the array is now sorted by score or wins/losses or whatever you put in it, the indices are all hoopajooped.
If you just walk through the array, grabbing the index of each entry, (look at the asort example. that for loop does just that) then the index you get will point right back to one of the values of the multi-dimensional array.
Not sure if that’s clear, but mail me if it isn’t.
-mo

I have two servers; one running 5.6 and another that is running 7. Using this function on the two servers gets me different results when all of the values are the same.

?>

PHP 5.6 results:
Array ( [706] => 2 [703] => 2 [702] => 2 [696] => 2 [658] => 2 )
Array ( [658] => 2 [696] => 2 [702] => 2 [703] => 2 [706] => 2 )

PHP 7 results:
Array ( [706] => 2 [703] => 2 [702] => 2 [696] => 2 [658] => 2 )
Array ( [706] => 2 [703] => 2 [702] => 2 [696] => 2 [658] => 2 )

Needed to get the index of the max/highest value in an assoc array.
max() only returned the value, no index, so I did this instead.

reset ( $x ); // optional.
arsort ( $x );
$key_of_max = key ( $x ); // returns the index.
?>

I was having trouble with the arsort() function on an older version of PHP which was returning an error along the lines of ‘wrong perameter count for function arsort’ when I tried to use a flag for numeric sorting (2/SORT_NUMERIC).
I figured, as I only wanted to sort integers, I could pad numbers from the left to a specific length with 0’s (using the lpad function provided by improv@magma.ca in the notes at http://www.php.net/manual/ref.strings.php).
A string sort then correctly sorts numerically (i.e. becomes not ) when echoing the number an (int)$string_name hides the leading 0’s.

A lot of people seem to trip up on this and ask me questions as to debugging. Bear in mind that this returns boolean, and does not return an array of affected items.

$array = array(«One»=>1, «Three» => 3,»Two» =>2);
print_r(asort($array));

If successful, will return 1, and error if there is a string used. Useful to note so then people stop asking me 😀

If you are dealing with a multidimensional array you want to sort, then this might be helpfull:

function array_sort ( $arr ) if(empty( $arr )) return $arr ;
foreach( $arr as $k => $a ) if(! is_array ( $a )) arsort ( $arr ); // could be any kind of sort
return $arr ;
>else $arr [ $k ] = array_sort ( $a );
>
>
return $arr ;
>
?>

  • Array Functions
    • array_​change_​key_​case
    • array_​chunk
    • array_​column
    • array_​combine
    • array_​count_​values
    • array_​diff_​assoc
    • array_​diff_​key
    • array_​diff_​uassoc
    • array_​diff_​ukey
    • array_​diff
    • array_​fill_​keys
    • array_​fill
    • array_​filter
    • array_​flip
    • array_​intersect_​assoc
    • array_​intersect_​key
    • array_​intersect_​uassoc
    • array_​intersect_​ukey
    • array_​intersect
    • array_​is_​list
    • array_​key_​exists
    • array_​key_​first
    • array_​key_​last
    • array_​keys
    • array_​map
    • array_​merge_​recursive
    • array_​merge
    • array_​multisort
    • array_​pad
    • array_​pop
    • array_​product
    • array_​push
    • array_​rand
    • array_​reduce
    • array_​replace_​recursive
    • array_​replace
    • array_​reverse
    • array_​search
    • array_​shift
    • array_​slice
    • array_​splice
    • array_​sum
    • array_​udiff_​assoc
    • array_​udiff_​uassoc
    • array_​udiff
    • array_​uintersect_​assoc
    • array_​uintersect_​uassoc
    • array_​uintersect
    • array_​unique
    • array_​unshift
    • array_​values
    • array_​walk_​recursive
    • array_​walk
    • array
    • arsort
    • asort
    • compact
    • count
    • current
    • end
    • extract
    • in_​array
    • key_​exists
    • key
    • krsort
    • ksort
    • list
    • natcasesort
    • natsort
    • next
    • pos
    • prev
    • range
    • reset
    • rsort
    • shuffle
    • sizeof
    • sort
    • uasort
    • uksort
    • usort
    • each

    Источник

    Sorting Arrays

    PHP has several functions that deal with sorting arrays, and this document exists to help sort it all out.

    • Some sort based on the array keys, whereas others by the values: $array[‘key’] = ‘value’;
    • Whether or not the correlation between the keys and values are maintained after the sort, which may mean the keys are reset numerically (0,1,2 . )
    • The order of the sort: alphabetical, ascending (low to high), descending (high to low), natural, random, or user defined
    • Note: All of these sort functions act directly on the array variable itself, as opposed to returning a new sorted array
    • If any of these sort functions evaluates two members as equal then they retain their original order. Prior to PHP 8.0.0, their order were undefined (the sorting was not stable).

    Sorting function attributes

    Function name Sorts by Maintains key association Order of sort Related functions
    array_multisort() value string keys yes, int keys no first array or sort options array_walk()
    asort() value yes ascending arsort()
    arsort() value yes descending asort()
    krsort() key yes descending ksort()
    ksort() key yes ascending krsort()
    natcasesort() value yes natural, case insensitive natsort()
    natsort() value yes natural natcasesort()
    rsort() value no descending sort()
    shuffle() value no random array_rand()
    sort() value no ascending rsort()
    uasort() value yes user defined uksort()
    uksort() key yes user defined uasort()
    usort() value no user defined uasort()

    User Contributed Notes 2 notes

    While this may seem obvious, user-defined array sorting functions ( uksort(), uasort(), usort() ) will *not* be called if the array does not have *at least two values in it*.

    function usortTest ( $a , $b ) var_dump ( $a );
    var_dump ( $b );
    return — 1 ;
    >

    $test = array( ‘val1’ );
    usort ( $test , «usortTest» );

    $test2 = array( ‘val2’ , ‘val3’ );
    usort ( $test2 , «usortTest» );

    The first array doesn’t get sent to the function.

    Please, under no circumstance, place any logic that modifies values, or applies non-sorting business logic in these functions as they will not always be executed.

    Another way to do a case case-insensitive sort by key would simply be:

    uksort ( $array , ‘strcasecmp’ );
    ?>

    Since strcasecmp is already predefined in php it saves you the trouble to actually write the comparison function yourself.

    Источник

    PHP Sorting Arrays

    The elements in an array can be sorted in alphabetical or numerical order, descending or ascending.

    PHP — Sort Functions For Arrays

    In this chapter, we will go through the following PHP array sort functions:

    • sort() — sort arrays in ascending order
    • rsort() — sort arrays in descending order
    • asort() — sort associative arrays in ascending order, according to the value
    • ksort() — sort associative arrays in ascending order, according to the key
    • arsort() — sort associative arrays in descending order, according to the value
    • krsort() — sort associative arrays in descending order, according to the key

    Sort Array in Ascending Order — sort()

    The following example sorts the elements of the $cars array in ascending alphabetical order:

    Example

    The following example sorts the elements of the $numbers array in ascending numerical order:

    Example

    Sort Array in Descending Order — rsort()

    The following example sorts the elements of the $cars array in descending alphabetical order:

    Example

    The following example sorts the elements of the $numbers array in descending numerical order:

    Example

    Sort Array (Ascending Order), According to Value — asort()

    The following example sorts an associative array in ascending order, according to the value:

    Example

    Sort Array (Ascending Order), According to Key — ksort()

    The following example sorts an associative array in ascending order, according to the key:

    Example

    Sort Array (Descending Order), According to Value — arsort()

    The following example sorts an associative array in descending order, according to the value:

    Example

    Sort Array (Descending Order), According to Key — krsort()

    The following example sorts an associative array in descending order, according to the key:

    Example

    Complete PHP Array Reference

    For a complete reference of all array functions, go to our complete PHP Array Reference.

    The reference contains a brief description, and examples of use, for each function!

    Источник

    array_reverse

    Takes an input array and returns a new array with the order of the elements reversed.

    Parameters

    If set to true numeric keys are preserved. Non-numeric keys are not affected by this setting and will always be preserved.

    Return Values

    Returns the reversed array.

    Examples

    Example #1 array_reverse() example

    $input = array( «php» , 4.0 , array( «green» , «red» ));
    $reversed = array_reverse ( $input );
    $preserved = array_reverse ( $input , true );

    print_r ( $input );
    print_r ( $reversed );
    print_r ( $preserved );
    ?>

    The above example will output:

    Array ( [0] => php [1] => 4 [2] => Array ( [0] => green [1] => red ) ) Array ( [0] => Array ( [0] => green [1] => red ) [1] => 4 [2] => php ) Array ( [2] => Array ( [0] => green [1] => red ) [1] => 4 [0] => php )

    See Also

    User Contributed Notes

    • Array Functions
      • array_​change_​key_​case
      • array_​chunk
      • array_​column
      • array_​combine
      • array_​count_​values
      • array_​diff_​assoc
      • array_​diff_​key
      • array_​diff_​uassoc
      • array_​diff_​ukey
      • array_​diff
      • array_​fill_​keys
      • array_​fill
      • array_​filter
      • array_​flip
      • array_​intersect_​assoc
      • array_​intersect_​key
      • array_​intersect_​uassoc
      • array_​intersect_​ukey
      • array_​intersect
      • array_​is_​list
      • array_​key_​exists
      • array_​key_​first
      • array_​key_​last
      • array_​keys
      • array_​map
      • array_​merge_​recursive
      • array_​merge
      • array_​multisort
      • array_​pad
      • array_​pop
      • array_​product
      • array_​push
      • array_​rand
      • array_​reduce
      • array_​replace_​recursive
      • array_​replace
      • array_​reverse
      • array_​search
      • array_​shift
      • array_​slice
      • array_​splice
      • array_​sum
      • array_​udiff_​assoc
      • array_​udiff_​uassoc
      • array_​udiff
      • array_​uintersect_​assoc
      • array_​uintersect_​uassoc
      • array_​uintersect
      • array_​unique
      • array_​unshift
      • array_​values
      • array_​walk_​recursive
      • array_​walk
      • array
      • arsort
      • asort
      • compact
      • count
      • current
      • end
      • extract
      • in_​array
      • key_​exists
      • key
      • krsort
      • ksort
      • list
      • natcasesort
      • natsort
      • next
      • pos
      • prev
      • range
      • reset
      • rsort
      • shuffle
      • sizeof
      • sort
      • uasort
      • uksort
      • usort
      • each

      Источник

    Читайте также:  Programming abstractions in java
Оцените статью