自然排序一个关联数组? [英] Natural sort an associative array?

查看:58
本文介绍了自然排序一个关联数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个数组数组,我将如何根据其值对内部数组进行自然排序?

Given an array of arrays, how would I natural sort the inner arrays based on their values?

示例数组:

array (size=2)
  0 => 
    array (size=1)
      'manager' => string 'Manager 1' (length=9)
  1 => 
    array (size=1)
      'manager' => string 'Manager 3' (length=9)

另一个示例数组:

array (size=2)
  0 => 
    array (size=1)
      'month' => string 'June' (length=4)
  1 => 
    array (size=1)
      'month' => string 'January' (length=7)

我的第一个想法是只natsort()它们,但是那需要一个普通的数组.下一个想法是使用array_multisort($array, SORT_NATURAL);,但是由于有关联数组,所以没有用.

My first idea was to just natsort() them, but that expects a normal array. The next idea was to use array_multisort($array, SORT_NATURAL);, but that didn't work due to the associative arrays.

那么,如何使用自然排序对内部数组进行排序?另外,在这种情况下,保持数组键无关紧要.

So, how could I sort the inner arrays in using natural sorting? Also, keeping array keys doesn't matter in this case.

数组1的预期输出将是相同的(因为Manager 1和Manager 3已经在顺序中):

Expected output of array 1 would be the same (since Manager 1 and Manager 3 are already in order):

array (size=2)
  0 => 
    array (size=1)
      'manager' => string 'Manager 1' (length=9)
  1 => 
    array (size=1)
      'manager' => string 'Manager 3' (length=9)

第二个数组的预期输出将把1月提前到6月(自然"顺序):

Expected output of array two would put January ahead of June (the 'natural' order):

// 0 and 1 keys can switch or stay the same, doesn't matter
array (size=2)
  0 => 
    array (size=1)
      'month' => string 'January' (length=4)
  1 => 
    array (size=1)
      'month' => string 'June' (length=7)

推荐答案

好!,您可以使用如下自然排序函数来简化函数:

Well!, You can simplify the function using natural sort functions like this:

usort($array, function($a, $b){
    return strnatcmp($a['manager'],$b['manager']); //Case sensitive
    //return strnatcasecmp($a['manager'],$b['manager']); //Case insensitive
});

这篇关于自然排序一个关联数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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