A simple method to implement multi-dimensional array sorting in PHP

高洛峰
Release: 2023-03-03 18:16:01
Original
1169 people have browsed it

The example in this article describes how to simply implement multi-dimensional array sorting in PHP. Share it with everyone for your reference, the details are as follows:

When I was doing a function before, I had to put the data into a two-dimensional array and sort it, and then go online to find solutions.

The array_multisort function will be used at this time. The array_multisort() function sorts multiple arrays or multi-dimensional arrays

Let’s look at an example first

<?php
$data=array(
0=>array(&#39;one&#39;=>34,&#39;two&#39;=>&#39;d&#39;),
1=>array(&#39;one&#39;=>45,&#39;two&#39;=>&#39;e&#39;),
2=>array(&#39;one&#39;=>47,&#39;two&#39;=>&#39;h&#39;),
3=>array(&#39;one&#39;=>12,&#39;two&#39;=>&#39;c&#39;),
4=>array(&#39;one&#39;=>15,&#39;two&#39;=>&#39;w&#39;),
5=>array(&#39;one&#39;=>85,&#39;two&#39;=>&#39;r&#39;),
);
foreach($data as $val){
$key_arrays[]=$val[&#39;one&#39;];
}
array_multisort($key_arrays,SORT_ASC,SORT_NUMERIC,$data);
var_dump($data);
Copy after login

The output result: Sort by key value one, as follows:

array
 0 => 
  array
   &#39;one&#39; => int 12
   &#39;two&#39; => string &#39;c&#39; (length=1)
 1 => 
  array
   &#39;one&#39; => int 15
   &#39;two&#39; => string &#39;w&#39; (length=1)
 2 => 
  array
   &#39;one&#39; => int 34
   &#39;two&#39; => string &#39;d&#39; (length=1)
 3 => 
  array
   &#39;one&#39; => int 45
   &#39;two&#39; => string &#39;e&#39; (length=1)
 4 => 
  array
   &#39;one&#39; => int 47
   &#39;two&#39; => string &#39;h&#39; (length=1)
 5 => 
  array
   &#39;one&#39; => int 85
   &#39;two&#39; => string &#39;r&#39; (length=1)
Copy after login

php Multi-dimensional array sort

The following is encapsulated into a function for easy use

function my_array_multisort($data,$sort_order_field,$sort_order=SORT_ASC,$sort_type=SORT_NUMERIC){
foreach($data as $val){
$key_arrays[]=$val[$sort_order_field];
}
array_multisort($key_arrays,SORT_ASC,SORT_NUMERIC,$data);
rturn $data;
}
Copy after login

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

For more articles on how to simply implement multi-dimensional array sorting in PHP, please pay attention to the PHP Chinese website!


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!