开发者

Sorting a 3 dimensional array

开发者 https://www.devze.com 2023-02-23 12:19 出处:网络
I\'ve got an array like this Array ( [0] => Array ( [0] => Array ( [szam] => 8 [index] => 0 ) ) [1] => Array

I've got an array like this

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [szam] => 8
                    [index] => 0
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                   开发者_如何学Go [szam] => 1
                    [index] => 0
                )

            [1] => Array
                (
                    [szam] => 7
                    [index] => 1
                )

        )

I thought that my last cmp will work fine

function maxSzerintCsokkeno($item1,$item2)
{
    if ($item1['szam'] == $item2['szam']) return 0;
    return ($item1['szam'] < $item2['szam']) ? 1 : -1;
}

with 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. And this only exists temporarily until foreach loops over the next one. 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.


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. Like Tim Cooper said, you are actually sorting a copy of the original value.

You can also pass the value by reference in your foreach loop. This means that you will be modifying the original value:

foreach ($tomb as $kulcs => &$adat)  usort($adat,"maxSzerintCsokkeno");
0

精彩评论

暂无评论...
验证码 换一张
取 消