phparrayssortingmultidimensional-arrayassociative

Call class method by string name as callback of a native function within another class method


I know this question has been asked before, but not in this context (OOP):

class XYZ {

    public function index() {

        $array = [
            [
                'id' => 1,
                'name' => 'Alpha'
            ],
            [
                'id' => 2,
                'name' => 'Beta'
            ],
            [
                'id' => 3,
                'name' => 'Gamma'
            ]
        ];

        $newArray = usort($array, 'modify');

        return $newArray;

    }

    public function modify($a, $b) {

        return $b['name'] - $a['name'];

    }

}

This indexAction returns an empty array, and I am not sure why.


Solution

  • Over here within your usort function the second parameter consist of two values first one ClassName and the other one functionName so your second parameter looks like as

    usort($array,['ClassName','functionName']);
    

    Which in your case it'll be like as

    usort($array,['XYZ','modify']);
    

    Demo