Skip to main content

Function to sort multi dimensional array based on column from child array (PHP)

Sometimes we need the ability to sort an array depending on the value of column from child array.
Below method will allow you to get it done.

/*
 * Generic multi dimensional array sorter
 * Requires PHP 7.x for the spaceship operators
 */
 function sortData(&$data, $datakey, $sortOrder = 'asc')

 {
     function generic_sorter($datakey, $sortOrder)
     {
         return function ($a, $b) use ($datakey, $sortOrder) {
             return ($sortOrder  == 'desc') ? ($b[$datakey] <=> $a[$datakey])
             : ($a[$datakey] <=> $b[$datakey]);
         };
     }
   
     $datakey = strtolower(trim($datakey));
     $sortOrder = strtolower(trim($sortOrder));
     $firstArr = reset($data);
     if (($sortOrder !== 'asc' && $sortOrder !== 'desc')
         || (!empty($data) && empty($firstArr[$datakey]))) {
         Throw new Exception('invalid sort order or data key given');
     }
     // sort data element inplace using generic sorter
     usort($data, generic_sorter($datakey, $sortOrder)); 
 }

Example


 try {
         
            $a = [
                [
                    'f' => '4',
                    's' => '1',
                    't' => '10'
                ],
                [
                    'f' => '3',
                    's' => '2',
                    't' => '5'
                ],
                [
                    'f' => '1',
                    's' => '4',
                    't' => '3'
                ],
                [
                    'f' => '2',
                    's' => '3',
                    't' => '1'
                ]
            ];
            echo '<pre>before:';
            print_r($a);
         
            sortData($a, 't', 'asc');
            echo "\nAfter:";
            print_r($a);
        } catch (Exception $e) {
            echo $e->getMessage();
        }

output: array sorted by column 't' in ascending order

before:Array
(
    [0] => Array
        (
            [f] => 4
            [s] => 1
            [t] => 10
        )

    [1] => Array
        (
            [f] => 3
            [s] => 2
            [t] => 5
        )

    [2] => Array
        (
            [f] => 1
            [s] => 4
            [t] => 3
        )

    [3] => Array
        (
            [f] => 2
            [s] => 3
            [t] => 1
        )

)

After:Array
(
    [0] => Array
        (
            [f] => 2
            [s] => 3
            [t] => 1
        )

    [1] => Array
        (
            [f] => 1
            [s] => 4
            [t] => 3
        )

    [2] => Array
        (
            [f] => 3
            [s] => 2
            [t] => 5
        )

    [3] => Array
        (
            [f] => 4
            [s] => 1
            [t] => 10
        )

)

Comments

  1. Play Real Money Online Casinos | No Deposit Bonuses 2021
    No deposit bonuses are a type of bonus offered by online kadangpintar casinos without actually needing to deposit anything 1xbet korean at all. You can 인카지노 earn the money you spend with these bonuses on

    ReplyDelete
  2. How To Make Money On Sports Betting
    Online sports betting is available หารายได้เสริม for a whole host of US and European sports betting markets. Some US 출장안마 states, https://deccasino.com/review/merit-casino/ like wooricasinos.info Louisiana and New Jersey, allow

    ReplyDelete
  3. Vampires in the Enchanted Castle casino - FilmFileEurope
    Vampires in 토토 사이트 the poormansguidetocasinogambling Enchanted Castle Casino. jancasino.com Vampires in the Enchanted Castle Casino. Vampires in the Enchanted Castle Casino. Vampires in the Enchanted Castle Casino. Vampires in the sol.edu.kg Enchanted ventureberg.com/

    ReplyDelete
  4. Since just one pack of cards is used, players can rely on chance theory when deciding whether to face or hit. Live Casino video games work equally to classic video games, however suppliers like Pragmatic Play Live, Quick and Evolution go above and past to deliver extraordinary video games. The well-known Live Poker tables are here, the classic reside Hold’em poker, three card poker and more – strive your hand with us. More video games, more tournaments and so many poker tables, it takes two flooring to carry all of them. Remember to use your card every time you play to start earning the presents and benefits 1xbet korea you deserve. Join us forPhilly Wine Fest, theUltimate Wine Tasting Experience.

    ReplyDelete
  5. » You need to be aware of|to focus on|to concentrate to} the significance of betting positions. For example, betting first on an elimination hand or on the ultimate hand places you at a definite drawback in comparison with} betting final. » You need to know when it is best to guess massive, i.e., guess so much you've got got} probably the most chips when everybody wins. » You gain an advantage by understanding how to 1xbet to|tips on how to} play higher than your opponents.

    ReplyDelete
  6. Fortune Coin Co. and its video slot-machine expertise had been bought by IGT in 1978. Digital expertise has resulted in variations within the original slot machine idea. As the player is basically taking part in} a online game, producers can provide more interactive components, such as superior bonus rounds and more varied video graphics. Where gamers play the identical slot machine sport to see 우리카지노 who wins the most cash. A percentage figure displaying how a lot cash the slot sport pays again. For example, the Gonzo’s Quest slot has an RTP of 96%, that means you'll get again $96 for each $100 bet.

    ReplyDelete
  7. Investopedia does not embody all offers out there in the marketplace. To say on line casino gambling is a lucrative enterprise thecasinosource.com can be an understatement. In 2020, industrial on line casino gaming revenue amounted to about $30 billion, a virtually 30% decline from 2019 end result of} COVID-19 pandemic after a seven-year interval of regular year-over-year progress. Yarilet Perez is an experienced multimedia journalist and fact-checker with a Master of Science in Journalism. She has labored in quantity of} cities overlaying breaking news, politics, schooling, and more. Her experience is in personal finance and investing, and actual property.

    ReplyDelete

Post a Comment