[英]PHP trying to sort an array in an array
// 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);
});
}
As you can see we are trying to sort an array by keys, then the blocks within an array by the value start_time 如您所见,我们试图按键对数组进行排序,然后按值start_time对数组中的块进行排序
This is how the array looks like 这是数组的样子
[
"2015-04-25" => [
"blocks" => [
$object1,
$object2,
$object3
]
]
]
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... 经过一些调试后,我意识到问题是对块的修改未反映在原始$ unavailable数组中,它没有引用似乎相同的数组...
For example: 例如:
foreach($unavailable as $each) {
$each['blocks'] = null;
}
// $unavaiable[$date]['blocks'] still has original object(s)
What is the solution? 解决办法是什么?
Solution is: 解决方法是:
foreach ($unavailable as &$each) // see that & here?
Adding &
to $each
means that all changes made to $each
will be applied to elements of $unavailable
. 添加
&
到$each
意味着对所做的所有更改$each
将被应用到的元素$unavailable
。
Reference it to the parent 引用给父母
foreach($unavailable as $key => $each) {
usort($unavailable[$key]['blocks'], function($a, $b) {
return strcmp($a->start_time, $b->start_time);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.