skip to Main Content

I want to sort a php associative array according to price in case of token and yearly price in case of subscription plan

Here is the exmaple:

    $packs = [
        [
            'name' => 'starter',
            'type' => 'token',
            'price' => 199
        ],
        [
            'name' => 'business',
            'type' => 'subscription',
            'price' => [
                'monthly' => 19,
                'yearly' => 219,
            ]
        ],
        [
            'name' => 'professional',
            'type' => 'subscription',
            'price' => [
                'monthly' => 9,
                'yearly' => 119,
            ]
        ],
    ]

I want to get a result like this

    [
        [
            'name' => 'professional',
            'type' => 'subscription',
            'price' => [
                'monthly' => 9,
                'yearly' => 119,
            ]
        ],
        [
            'name' => 'starter',
            'type' => 'token',
            'price' => 199
        ],
        [
            'name' => 'business',
            'type' => 'subscription',
            'price' => [
                'monthly' => 19,
                'yearly' => 219,
            ]
        ],
    ]

I tried this kind of solution but it returned an array with price in the key, but don’t need price as key

    $price = [];

    foreach( $packs as $key => $value ){
        if( $value['type'] == 'token' ){
            $price[intval($value['price'])] = $value;
        }
        if( $value['type'] == 'subscription' ){
            $price[intval($value['price']['yearly'])] = $value;
        }
    }
    krsort( $price );

    $new_packs = [];
    foreach($price as $k => $value){
        $new_packs[] = $k;
    }

    //print_r($new_packs) // it returned same as the given array

2

Answers


  1. usort($packs, function ($a, $b) { 
        return $a['price']['yearly'] ?? $a['price'] <=> $b['price']['yearly'] ?? $b['price']; 
    });
    
    Login or Signup to reply.
  2. but it returned an array with price in the key, but don’t need price as key Ok, but you are literally doing it in $price[intval($value['price'])] = and likewise.

    Don’t use krsort. Use ksort (Since you want the ordering in ascending order)

    Also, you just have to use $value instead of $k to take only the array values like below, because key => value is the syntax for foreach and here $k is your key and $value is your value.

    <?php
    
    $new_packs = [];
    foreach($price as $k => $value){
        $new_packs[] = $value;
    }
    

    OR

    A better alternative is to simply use array_values like below:

    $new_packs = array_values($price);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search