How to sort an array of associative arrays by value of a given key in PHP?

前端 未结 19 1817
清酒与你
清酒与你 2020-11-21 23:34

Given this array:

$inventory = array(

   array(\"type\"=>\"fruit\", \"price\"=>3.50),
   array(\"type\"=>\"milk\", \"price\"=>2.90),
   array(\"         


        
19条回答
  •  一向
    一向 (楼主)
    2020-11-22 00:31

    $arr1 = array(
    
        array('id'=>1,'name'=>'aA','cat'=>'cc'),
        array('id'=>2,'name'=>'aa','cat'=>'dd'),
        array('id'=>3,'name'=>'bb','cat'=>'cc'),
        array('id'=>4,'name'=>'bb','cat'=>'dd')
    );
    
    $result1 = array_msort($arr1, array('name'=>SORT_DESC);
    
    $result2 = array_msort($arr1, array('cat'=>SORT_ASC);
    
    $result3 = array_msort($arr1, array('name'=>SORT_DESC, 'cat'=>SORT_ASC));
    
    
    function array_msort($array, $cols)
    {
        $colarr = array();
        foreach ($cols as $col => $order) {
        $colarr[$col] = array();
        foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
    }
    
    $eval = 'array_multisort(';
    
    foreach ($cols as $col => $order) {
        $eval .= '$colarr[\''.$col.'\'],'.$order.',';
    }
    
    $eval = substr($eval,0,-1).');';
    eval($eval);
    $ret = array();
    foreach ($colarr as $col => $arr) {
        foreach ($arr as $k => $v) {
            $k = substr($k,1);
            if (!isset($ret[$k])) $ret[$k] = $array[$k];
            $ret[$k][$col] = $array[$k][$col];
        }
    }
    return $ret;
    
    
    } 
    

提交回复
热议问题