一道面试题:
当然,正常的一维数组其实是有sort(),asort(),arsort()等函数可以排序的(其实我最常用的就是sort了,后面俩基本没用过……惭愧惭愧)。
它可以对二维数组按照指定的键值进行排序,也可以指定升序或降序排序法(默认为升序),示例:
$v){
$keysvalue[$k] = $v[$keys];
}
var_dump($keysvalue);
echo ‘
‘;
if($type == ‘asc’){
asort($keysvalue);
}else{
arsort($keysvalue);
}
var_dump($keysvalue);
echo ‘
‘;
reset($keysvalue);
foreach ($keysvalue as $k=>$v){
$new_array[$k] = $arr[$k];
}
return $new_array;
}
$array = array(
array(‘name’=>’手机’,’brand’=>’诺基亚’,’price’=>1050),
array(‘name’=>’笔记本电脑’,’brand’=>’lenovo’,’price’=>4300),
array(‘name’=>’剃须刀’,’brand’=>’飞利浦’,’price’=>3100),
array(‘name’=>’跑步机’,’brand’=>’三和松石’,’price’=>4900),
array(‘name’=>’手表’,’brand’=>’卡西欧’,’price’=>960),
array(‘name’=>’液晶电视’,’brand’=>’索尼’,’price’=>6299),
array(‘name’=>’激光打印机’,’brand’=>’惠普’,’price’=>1200)
);
$ShoppingList = array_sort($array,’price’);
var_dump($ShoppingList);
echo ‘
‘;
?>

输出结果:

array(7) { [0]=> int(1050) [1]=> int(4300) [2]=> int(3100) [3]=> int(4900) [4]=> int(960) [5]=> int(6299) [6]=> int(1200) }
array(7) { [4]=> int(960) [0]=> int(1050) [6]=> int(1200) [2]=> int(3100) [1]=> int(4300) [3]=> int(4900) [5]=> int(6299) }
array(7) { [4]=> array(3) { ["name"]=> string(6) "手表" ["brand"]=> string(9) "卡西欧" ["price"]=> int(960) } [0]=> array(3) { ["name"]=> string(6) "手机" ["brand"]=> string(9) "诺基亚" ["price"]=> int(1050) } [6]=> array(3) { ["name"]=> string(15) "激光打印机" ["brand"]=> string(6) "惠普" ["price"]=> int(1200) } [2]=> array(3) { ["name"]=> string(9) "剃须刀" ["brand"]=> string(9) "飞利浦" ["price"]=> int(3100) } [1]=> array(3) { ["name"]=> string(15) "笔记本电脑" ["brand"]=> string(6) "lenovo" ["price"]=> int(4300) } [3]=> array(3) { ["name"]=> string(9) "跑步机" ["brand"]=> string(12) "三和松石" ["price"]=> int(4900) } [5]=> array(3) { ["name"]=> string(12) "液晶电视" ["brand"]=> string(6) "索尼" ["price"]=> int(6299) } }

如果你对其中的foreach有些不明白的话,可以参考昨天的日志:PHP中foreach循环示例详解

Related Posts: PHP二维数组排序函数 :