Home  >  Article  >  Backend Development  >  PHP method to sort a two-dimensional array by specified key value, _PHP tutorial

PHP method to sort a two-dimensional array by specified key value, _PHP tutorial

WBOY
WBOYOriginal
2016-07-12 09:02:38902browse

PHP’s method of sorting two-dimensional arrays by specified key values,

The example in this article describes the method of PHP sorting two-dimensional arrays by specified key values. Share it with everyone for your reference, the details are as follows:

Question:

There is an array: Copy code The code is as follows: array(0=>array('id'=>1,'price'=>50),1= >array('id'=>2,'price'=>60));
It is required to sort based on the price field of the array.

The implementation code is as follows:

<&#63;php 
$array[] = array('id'=>1,'price'=>50);
$array[] = array('id'=>2,'price'=>70);
$array[] = array('id'=>3,'price'=>30);
$array[] = array('id'=>4,'price'=>20);
foreach ($array as $key=>$value){
  $id[$key] = $value['id'];
  $price[$key] = $value['price'];
}
array_multisort($price,SORT_NUMERIC,SORT_DESC,$id,SORT_STRING,SORT_ASC,$array);
echo '<pre class="brush:php;toolbar:false">';
print_r($array);
echo '
'; ?>

Run result:

Array
(
[0] => Array
(
[id] => 2
[price] => 70
)
[1] => Array
(
[id] => 1
[price] => 50
)
[2] => Array
(
[id] => 3
[price] => 30
)
[3] => Array
(
[id] => 4
[price] => 20
)
)

I hope this article will be helpful to everyone in PHP programming.

Articles you may be interested in:

  • php method to delete duplicate elements in an array
  • php submit post array parameter example analysis
  • php array function array_key_exists () Summary
  • PHP multi-dimensional array traversal method (2 implementation methods)
  • Summary of some commonly used add, delete, and insert operation functions for arrays in PHP
  • Detailed explanation of PHP Definition of arrays and methods of creating arrays
  • Implementing random merging of arrays and sorting (original sorting) based on PHP
  • PHP method of traversing multi-dimensional arrays
  • PHP multi-dimensional array conversion Simple implementation method of one-dimensional array

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1084567.htmlTechArticlePHP method of sorting two-dimensional arrays by specified key values. This article describes the example of PHP sorting two-dimensional arrays by specified key values. How to sort a two-dimensional array. Share it with everyone for your reference, the details are as follows:...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn