Sort array by value in associative php

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.

Читайте также:  Joomla php version support

Источник

Sorting Associative Arrays

It’s often desirable to keep the key/value associations when sorting associative arrays. To maintain the key/value association the asort( ) and arsort( ) functions are used. Rather than sort on element values, the ksort( ) and krsort( ) functions rearrange elements in an array by sorting on the keys or the indexes.

  1. array as input
  2. Sorting flags (optional) to modify the behavior of the sort.

asort Sort associative arrays by values in ascending order

 'II','four' => 'IV', 'three' => 'III', 'one' => 'I']; asort($a); print_r($a); /* Prints Array ( [one] => I [two] => II [three] => III [four] => IV ) */

Like sort( ) this function rearranges the elements in the subject array from lowest to highest. The following example shows a simple array sorted by asort( ) :

"kk", "e"=>"zz", "z"=>"hh", "a"=>"rr"); asort($map); print_r($map);

The print_r( ) function outputs the structure of the sorted array:

Array ( [z] => hh [o] => kk [a] => rr [e] => zz )

When assort( ) and arsort( ) are used on nonassociative arrays, the order of the elements is arranged in sorted order, but the indexes that access the elements don’t change. This might seem a bit weird; effectively the indexes are treated as association keys in the resulting array. The following example shows what is happening:

Array ( [2] => 3 [5] => 8 [3] => 16 [1] => 19 [0] => 24 [4] => 56 [6] => 171 )

arsort Sort associative arrays by values in descending order

 'II','four' => 'IV', 'three' => 'III', 'one' => 'I']; arsort($a); print_r($a); /* Prints Array ( [four] => IV [three] => III [two] => II [one] => I ) */

Like rsort( ) this function rearranges the elements in the subject array from highest to lowest. The following example shows a simple array sorted by arsort( ) :

"kk", "e"=>"zz", "z"=>"hh", "a"=>"rr"); arsort($map); print_r($map); /* Prints Array ( [e] => zz [a] => rr [o] => kk [z] => hh ) */

Sorting Associative Arrays Alphabetically

24, 'nt'=>19, 'te'=>3, 'sn'=>16, 'fs'=>56, 'et'=>8, 'oso'=>171]; asort($a); print_r($a);

The output of the example shows the result:

//Numerically sorted Array ( [te] => 3 [et] => 8 [sn] => 16 [nt] => 19 [tf] => 24 [fs] => 56 [oso] => 171 )

By default, PHP sorts strings in alphabetical order and numeric values in numeric order. An optional parameter, sorting flag , can be passed to force the string or numeric sorting behavior. In the following example, the PHP constant SORT_STRING sorts the numbers as if they were strings:

24, 'nt'=>19, 'te'=>3, 'sn'=>16, 'fs'=>56, 'et'=>8, 'oso'=>171]; asort($a, SORT_STRING); print_r($a);

The output of the example shows the result:

//Alphabetically sorted Array ( [sn] => 16 [oso] => 171 [nt] => 19 [tf] => 24 [te] => 3 [fs] => 56 [et] => 8 )

ksort Sort arrays by keys in ascending order

ksort( ) sorts the elements in an array from lowest key to highest key (in alphabetic order). The following example demonstrates the ksort( ) function.

 'II','four' => 'IV', 'three' => 'III', 'one' => 'I']; ksort($a); print_r($a); /* Prints Array ( [four] => IV [one] => I [three] => III [two] => II ) */

ksort() function, another example:

"kk", "e"=>"zz", "z"=>"hh", "a"=>"rr"); ksort($map); print_r($map); /* Prints Array ( [a] => rr [e] => zz [o] => kk [z] => hh ) */

krsort Sort arrays by keys in descending order

krsort( ) sorts the elements in the subject array from highest key to lowest key (in reverse alphabetic order). The following example demonstrates the krsort( ) function:

 'II','four' => 'IV', 'three' => 'III', 'one' => 'I']; krsort($a); print_r($a); /* Prints Array ( [two] => II [three] => III [one] => I [four] => IV )

krsort() function, another example:

"kk", "e"=>"zz", "z"=>"hh", "a"=>"rr"); krsort($map); print_r($map); /* Prints Array ( [z] => hh [o] => kk [e] => zz [a] => rr ) */

More Posts on PHP Sorting Arrays:

Читайте также:  Команда закончить код python

Источник

Sort an Array of Associative Arrays by Value of a Given Key in PHP

Sort an Array of Associative Arrays by Value of a Given Key in PHP

  1. Use array_multisort() Function to Sort an Array of Associative Arrays by the Value of a Given Key in PHP
  2. Use the usort() Function to Sort an Array of Associative Arrays by the Value of a Given Key in PHP

This article will introduce methods to sort an array of associative arrays by the value of a given key in PHP.

Use array_multisort() Function to Sort an Array of Associative Arrays by the Value of a Given Key in PHP

We can use the built-in function array_multisort() to sort an array of associative arrays by the value of a given key. It can sort many arrays at a time or a multidimensional array. The correct syntax to use this function is as follows

str_replace($arrayName, $sort_order, $sort_flags); 

This function returns TRUE if it is successful. Otherwise, it returns FALSE.

The program below shows how we can use the array_multisort() function to sort an array of associative arrays by the value of a given key.

php $result = array(   array("firstname"=>"Olivia", "marks"=>85),  array("firstname"=>"Jacob", "marks"=>60),  array("firstname"=>"Henry", "marks"=>100),  array("firstname"=>"Lili", "marks"=>40),  array("firstname"=>"Stefan", "marks"=>5),  array("firstname"=>"Bonnie", "marks"=>97), ); $marks = array(); foreach ($result as $key => $row)   $marks[$key] = $row['marks'];  > array_multisort($marks, SORT_DESC, $result); print_r($result); ?> 

We have created an array $marks containing the marks from the original array. After that, we have used the array_multisort() function to sort $marks array based on the $result array. The output will be the $result array sorted.

Array (  [0] => Array  (  [firstname] => Henry  [marks] => 100  )   [1] => Array  (  [firstname] => Bonnie  [marks] => 97  )   [2] => Array  (  [firstname] => Olivia  [marks] => 85  )   [3] => Array  (  [firstname] => Jacob  [marks] => 60  )   [4] => Array  (  [firstname] => Lili  [marks] => 40  )   [5] => Array  (  [firstname] => Stefan  [marks] => 5  )  ) 

The array is sorted in descending order by the value of the marks key.

Use the usort() Function to Sort an Array of Associative Arrays by the Value of a Given Key in PHP

In PHP, we can also use the usort() function to sort an array of associative arrays by the value of a given key. This function sorts the array using a user-defined function. The correct syntax to use this function is as follows:

preg_replace($arrayName, $functionName); 

It returns TRUE if successful, FALSE otherwise. The program that sorts the array is as follows:

php function DescSort($item1,$item2)   if ($item1['marks'] == $item2['marks']) return 0;  return ($item1['marks']  $item2['marks']) ? 1 : -1; > $result = array(   array("firstname"=>"Olivia", "marks"=>85),  array("firstname"=>"Jacob", "marks"=>60),  array("firstname"=>"Henry", "marks"=>100),  array("firstname"=>"Lili", "marks"=>40),  array("firstname"=>"Stefan", "marks"=>5),  array("firstname"=>"Bonnie", "marks"=>97), ); usort($result,'DescSort'); print_r($result); ?> 
Array (  [0] => Array  (  [firstname] => Henry  [marks] => 100  )   [1] => Array  (  [firstname] => Bonnie  [marks] => 97  )   [2] => Array  (  [firstname] => Olivia  [marks] => 85  )   [3] => Array  (  [firstname] => Jacob  [marks] => 60  )   [4] => Array  (  [firstname] => Lili  [marks] => 40  )   [5] => Array  (  [firstname] => Stefan  [marks] => 5  )  ) 

For ascending sort, the function will be:

php function AscSort($item1,$item2)   if ($item1['marks'] == $item2['marks']) return 0;  return ($item1['marks'] > $item2['marks']) ? 1 : -1; > $result = array(   array("firstname"=>"Olivia", "marks"=>85),  array("firstname"=>"Jacob", "marks"=>60),  array("firstname"=>"Henry", "marks"=>100),  array("firstname"=>"Lili", "marks"=>40),  array("firstname"=>"Stefan", "marks"=>5),  array("firstname"=>"Bonnie", "marks"=>97), ); usort($result,'AscSort'); print_r($result); ?> 
Array (  [0] => Array  (  [firstname] => Stefan  [marks] => 5  )   [1] => Array  (  [firstname] => Lili  [marks] => 40  )   [2] => Array  (  [firstname] => Jacob  [marks] => 60  )   [3] => Array  (  [firstname] => Olivia  [marks] => 85  )   [4] => Array  (  [firstname] => Bonnie  [marks] => 97  )   [5] => Array  (  [firstname] => Henry  [marks] => 100  )  ) 

Related Article — PHP Array

Источник

Оцените статью