Search code examples
phparrayssortingmultidimensional-array

Sort rows of a 2d array by a column value


I have the following array. I need to sort this array by the nested array key [id]:

Array ( 
[0] => Array ( [id] => 5 [category_id] => 12 )
[1] => Array ( [id] => 3 [category_id] => 12 )
[2] => Array ( [id] => 9 [category_id] => 12 )
[3] => Array ( [id] => 4 [category_id] => 12 )
)

Solution

  • you can do it like this

    foreach($arr as $val) {
        $ret[$val['id']] = $val['category_id'];
    }
    ksort($ret);
    

    in case you want to get the same array sorted then you can add the following code:

    foreach($ret as $key=>$val) {
        $newArr[] = array('id'=>$key,'category_id'=>$val);
    }