如何在php中对数组进行排序? [英] How to sort an array of arrays in php?

查看:33
本文介绍了如何在php中对数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 php 中,我有一个关联数组的数值数组:

In php I have a numerical array of associative arrays:

mainArray: 
[
  array1:['title':'Record a','order':'2'],
  array2:['title':'Record b','order':'4'],
  array3:['title':'Record c','order':'1'],
  array4:['title':'Record d','order':'3']
]

根据每个关联数组的顺序"值对 mainArray 进行排序的最简单方法是什么?

What is the simplest way to sort mainArray by the 'order' value of each associative array?

谢谢

推荐答案

您可以使用 usort 功能.从 PHP 5.4 开始,您可以使用闭包函数:

You can use usort function. Since PHP 5.4 you can use closure function:

usort($mainArray, function ($a, $b) {
  $a_val = (int) $a['order'];
  $b_val = (int) $b['order'];

  if($a_val > $b_val) return 1;
  if($a_val < $b_val) return -1;
  return 0;
});

或 PHP 版本 <5.4:

Or version for PHP < 5.4:

usort($mainArray, 'myCompare');

function myCompare($a, $b) {
  $a_val = (int) $a['order'];
  $b_val = (int) $b['order'];

  if($a_val > $b_val) return 1;
  if($a_val < $b_val) return -1;
  return 0;
}

这篇关于如何在php中对数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆