B-Teck!

お仕事からゲームまで幅広く

【PHP】連想配列とかオブジェクトのソート

多次元連想配列やオブジェクトを詰めた配列はusort関数でいい感じにソートする。
PHP: usort - Manual

多次元連想配列のソートをする場合

<?php
    //連想配列でのソート
    $test = [["price" => "30", "stock" => "100"],
             ["price" => "20", "stock" => "120"],
             ["price" => "10", "stock" => "115"]];
    
    //ソート
    usort($test, function ($a, $b) {
        return $a['price'] < $b['price'] ? -1 : 1;
        //逆順の場合はこっち
        //return  $a['price'] > $b['price'] ? -1 : 1;
    });    

    print_r($test);

オブジェクトを詰めた配列のソートをする場合

<?php
    class testClass{
        public $price;
        public $stock;
                
        function __construct($price,$stock){
            $this->price = $price;
            $this->stock = $stock;
        }
    }
    
    $test2 = [];
    $test2[] = new testClass("30","100");
    $test2[] = new testClass("20","120");
    $test2[] = new testClass("10","115");    
    
    usort($test2, function ($a, $b) {
        return $a->stock< $b->stock? -1 : 1;
    });    

    print_r($test2);