PHP - assoc命令数组中的数组排序 [英] PHP - sort arrays within assoc array

查看:109
本文介绍了PHP - assoc命令数组中的数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我答应你,我有一个关于PHP排序,包括看许多现有的SO QS <一个href=\"http://stackoverflow.com/questions/17364127/reference-all-basic-ways-to-sort-arrays-and-data-in-php\">this大型之一

我有一个PHP关联数组,字符串作为键。每个值是整数数组。我想整数每个阵列,在简单的升序数字顺序排序。我相信这应该是很容易的,我已经找到足够的例子,我认为我应该做正确的事,但它并不完全工作,所以有一个错字或我是白痴或东西...

I've got a PHP associative array, with strings as keys. Each value is an array of integers. I want to sort each array of integers, in simple ascending numerical order. I'm convinced this should be easy, and I've found enough examples that I think I should be doing the right thing, but it's not quite working, so there's a typo or I'm an idiot or something...

PHP:

//Each fruit corresponds to an array (series) of integers
$data = [
    'banana' => [
        1,3,2
    ],
    'orange' => [
        5,1,3
    ]
];

echo "Before sort:\n";
var_dump($data);

//For each fruit, I want to order the numbers
foreach ($data as $key => $series)
{
    //Sort array of integers
    sort($series);

    //NB I wasn't sure about value/reference details of foreach loops, so I also tried
    //retrieving a series into a variable, sorting, and then reassigning back to the same key
}

echo "\n\nAfter sort:\n";
var_dump($data);

输出:

Before sort:
array(2) {
  'banana' =>
  array(3) {
    [0] =>
    int(1)
    [1] =>
    int(3)
    [2] =>
    int(2)
  }
  'orange' =>
  array(3) {
    [0] =>
    int(5)
    [1] =>
    int(1)
    [2] =>
    int(3)
  }
}


After sort:
array(2) {
  'banana' =>
  array(3) {
    [0] =>
    int(1)
    [1] =>
    int(3)
    [2] =>
    int(2)
  }
  'orange' =>
  array(3) {
    [0] =>
    int(5)
    [1] =>
    int(1)
    [2] =>
    int(3)
  }
}

正如你所看到的,在输出整数数组内未进行排序。我究竟做错了什么? (PHP 5.5.9,Windows 7中)

As you can see, in the output the inner arrays of integers have not been sorted. What am I doing wrong? (PHP 5.5.9, Windows 7)

推荐答案

使用参考&安培;

foreach ($data as $key => &$series)
{
    //Sort array of integers
    sort($series);
    // OR
    // sort($data[$key]);
}

这篇关于PHP - assoc命令数组中的数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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