Search code examples
phparraysmultidimensional-arrayasort

How do I control the order of this multidimensional array, based on a particular value?


After reading several posts here about this subject, I am unable to find the exact answer to my problem.

My current array is:

Array
(
    [0] => Array
        (
            [Level] => Bronze
            [Name] => JP Morgan
            [Logo] => Logo
        )

    [1] => Array
        (
            [Level] => Bronze
            [Name] => NASDAQ OMX
            [Logo] => Logo
        )

    [2] => Array
        (
            [Level] => Platinum
            [Name] => Credit Suisse
            [Logo] => Logo
        )

    [3] => Array
        (
            [Level] => Silver
            [Name] => BNP Paribas
            [Logo] => Logo
        )

)

What I want is to have all sponsors sorted by [Level] of which the order is:

  • Platinum
  • Gold
  • Silver
  • Bronze

How do I do this?


Solution

  • You could define your own sorting function. For example, you'd specify your own custom order that you want it to follow:

    $sort_order = array('Platinum', 'Gold', 'Silver', 'Bronze');
    

    Pass your array with all your data into your custom sort function, and search for the value's key position (in this case, Level) in the sort order you've just defined:

    $array = array(
      array (
        'Level' => 'Bronze',
          'Name' => 'JP Morgan',
          'Logo' => 'Logo'
      ),
      array (
          'Level' => 'Bronze',
          'Name' => 'NASDAQ OMX',
          'Logo' => 'Logo'
      ),
      array (
          'Level' => 'Platinum',
          'Name' => 'Credit Suisse',
          'Logo' => 'Logo'
      ),
      array (
          'Level' => 'Silver',
          'Name' => 'BNP Paribas',
          'Logo' => 'Logo'
      ),
    );
    
    usort($array, function ($a, $b) use ($sort_order) {
        return array_search($a['Level'], $sort_order) - array_search($b['Level'], $sort_order);
    });
    
    print_r($array);
    

    Outputs:

    Array
    (
    [0] => Array
        (
            [Level] => Platinum
            [Name] => Credit Suisse
            [Logo] => Logo
        )
    
    [1] => Array
        (
            [Level] => Silver
            [Name] => BNP Paribas
            [Logo] => Logo
        )
    
    [2] => Array
        (
            [Level] => Bronze
            [Name] => NASDAQ OMX
            [Logo] => Logo
        )
    
    [3] => Array
        (
            [Level] => Bronze
            [Name] => Jp Morgan
            [Logo] => Logo
        )
    )