[英]Sorting a 3 dimensional array
I've got an array like this 我有一个像这样的数组
Array
(
[0] => Array
(
[0] => Array
(
[szam] => 8
[index] => 0
)
)
[1] => Array
(
[0] => Array
(
[szam] => 1
[index] => 0
)
[1] => Array
(
[szam] => 7
[index] => 1
)
)
I thought that my last cmp will work fine 我以为我的最后一个cmp可以正常工作
function maxSzerintCsokkeno($item1,$item2)
{
if ($item1['szam'] == $item2['szam']) return 0;
return ($item1['szam'] < $item2['szam']) ? 1 : -1;
}
with foreach 与foreach
foreach ($tomb as $kulcs => $adat) usort($adat,"maxSzerintCsokkeno");
but it dosen't do anything, advise? 但是它什么也没做,建议吗?
foreach ($tomb as $kulcs => $adat) usort($adat,"maxSzerintCsokkeno");
This only sorts the subarray array $adat. 这只会对子数组数组$ adat进行排序。 And this only exists temporarily until foreach loops over the next one.
这只是暂时存在,直到foreach循环到下一个。 The lazy option here would be to use a reference:
这里的懒惰选项是使用参考:
foreach ($tomb as & $adat) usort($adat,"maxSzerintCsokkeno");
Notice the &
. 注意
&
。 This way the modification on $adat will be applied directly in the parent array. 这样,对$ adat的修改将直接应用到父数组中。
You're sorting a temporary variable, meaning the changes are not applied. 您正在对一个临时变量进行排序,这意味着未应用更改。 The following should work for you:
以下应该为您工作:
for($i = 0, $length = count($tomb); $i < $length; $i++)
{
usort($tomb[$i], "maxSzerintCsokkeno");
}
When iterating through the foreach loop, the key and value variables ( $kulcs
and $adat
in your code) are copies of the actual values in the array. 在foreach循环中迭代时,键和值变量(代码中的
$kulcs
和$adat
)是数组中实际值的副本。 Like Tim Cooper said, you are actually sorting a copy of the original value. 就像蒂姆·库珀(Tim Cooper)所说的那样,您实际上是在对原始值的副本进行排序。
You can also pass the value by reference in your foreach loop. 您还可以在foreach循环中通过引用传递值。 This means that you will be modifying the original value:
这意味着您将要修改原始值:
foreach ($tomb as $kulcs => &$adat) usort($adat,"maxSzerintCsokkeno");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.