PHP尝试对数组中的数组进行排序 [英] PHP trying to sort an array in an array

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

问题描述

      // sort by day date keys
      ksort($unavailable);
      // sort time blocks of day by start_time
      foreach($unavailable as $each) {
        usort($each['blocks'], function($a, $b) {
          return strcmp($a->start_time, $b->start_time);
        });
      }

如您所见,我们正在尝试按键对数组进行排序,然后按值start_time对数组中的块进行排序

As you can see we are trying to sort an array by keys, then the blocks within an array by the value start_time

这是数组的样子

[
  "2015-04-25" => [
    "blocks" => [
      $object1,
      $object2,
      $object3
    ]
  ]
]

经过一些调试后,我意识到问题在于对块的修改未反映在原始$ unavailable数组中,它没有引用似乎相同的数组...

After some debugging I realized that the problem is the modifications to blocks is not reflected in the original $unavailable array, it is not referencing the same array it seems...

例如:

foreach($unavailable as $each) {
  $each['blocks'] = null;
}

// $unavaiable[$date]['blocks'] still has original object(s)

解决方案是什么?

推荐答案

解决方案是:

foreach ($unavailable as &$each) // see that & here?

$each中添加&意味着对$each所做的所有更改都将应用于$unavailable的元素.

Adding & to $each means that all changes made to $each will be applied to elements of $unavailable.

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

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