2

Here is the array,

array(
[0] => Array
        (
            [IdRedeemProduct] => Item-A
            [RedeemOptions] => Array
                (
                    [0] => Array
                        (
                            [Points] => 1000
                        )

                    [1] => Array
                        (
                            [Points] => 2000
                        )

                    [2] => Array
                        (
                            [Points] => 43000
                        )

                )

            [ProductType] => 1
        )
[1] => Array
        (
            [IdRedeemProduct] => Item-B
            [RedeemOptions] => Array
                (
                    [0] => Array
                        (
                            [Points] => 6200
                        )

                    [1] => Array
                        (
                            [Points] => 53000
                        )

                )

            [ProductType] => 1
        )
)

most of the usort examples are just 2 level dimension array. I couldn't find any example for 3 level.

In this case i wanted to sort the smallest points to show first. Item-A will be the first and Item-B will be the 2nd.

2 Answers 2

1
foreach ($filteredResults as $key => $row)
                    {
                        foreach ($row['RedeemOptions'] as $key2 => $option) {
                            $vc_array_name[$key] = $option['Points'];
                        }
                    }

array_multisort($vc_array_name, SORT_ASC, $filteredResults);

this is working...

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

1 Comment

This works nicely. Thank you. You do not need the index in the second loop though.
0

Try this:

  function sort_2d_desc($array, $key) {

    usort($array, function($a, $b) use ($key) {
        return strnatcasecmp($b[$key], $a[$key]);
    });

    return $array;
  }

       $a = [];
    foreach($arr as $key => $val){
        $a[$key] = $this->sort_2d_desc($val['RedeemOptions'], 'Points');
    }

    $newArr = [];
    foreach($arr as $key => $val){

        $newArr[] = ['IdRedeemProduct' => $val['IdRedeemProduct'], 'RedeemOptions' => $a, 'ProductType' => $val['ProductType']];
    }



    print_r($newArr);

10 Comments

return asort() expects parameter 1 to be array, null given. :(
Can you try it again?
this will only return the key instead of the value.. output: Array ( [0] => 1 [1] => 1 )
This seems like its only for two levels though right? You should just add another foreach statement with $val as $key => $thirdVal
@bravonet try changing that asort to sort
|

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.