2

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

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?

3 Answers 3

3
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.

Sign up to request clarification or add additional context in comments.

Comments

2

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");
}

Comments

0

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.