php数组倒叙支持多维数组

时间:2022-12-04 19:00:34
<?php
//一维数组
$test1 = array("a"=>"苹果","b"=>"香蕉","c"=>"芒果");

//二位数组
$test2[0] = array("id"=>"17","name"=>"汽车");
$test2[99] = array("id"=>"18","name"=>"飞机");
$test2[2] = array("id"=>"19","name"=>"高铁");
$test2[3] = array("id"=>"20","name"=>"高铁");

//三维数组
$test3 = array("aaa"=>$test1,"bbb"=>$test2);


/*
  arr:数组
  isvalues:是否将数组key值重新排列
*/

//数组倒叙
function array_rsort($arr,$isvalues=false)
{
	if(is_array($arr)){
		$flag = false;
		//一维数组
		if(count($arr) == count($arr,1)){
			$flag = true;
			$i = 0;
			//转换成二维数组
			foreach($arr AS $key=>$value){
				$a[$i]["okey"] = $key;
				$a[$i]["value"] = $value;
				$i++;
			}
			$arr = $a;
		}
		//多维数组
		else
		{
			//添加临时key值
			foreach($arr AS $key=>$value){
				$value["okey"] = $key;
				$array[] = $value;
			}
			$arr = $array;
		}
		
		//倒叙并还原key值
		$count = count($arr)-1;
		for($i=0;$i<count($arr);$i++){
			$b[$arr[$count]["okey"]] = $arr[$count];
			$count--;
		}
		
		//重构一维数组
		if($flag == true){
			foreach($b AS $key=>$value){
				if($isvalues){
					$c[] = $value["value"];
				}else{
					$c[$value["okey"]] = $value["value"];
				}
			}
		}
		//多维数组去除临时key值
		else
		{
			foreach($b AS $key=>$value)	{
				unset($value["okey"]);
				if($isvalues){
					$c[] = $value;
				}else{
					$c[$key] = $value;
				}
			}
		}
		return $c;
	}
}

var_dump(array_rsort($test1));
var_dump(array_rsort($test1,true));
echo "----------------------------------------";
var_dump(array_rsort($test2));
var_dump(array_rsort($test2,true));
echo "----------------------------------------";
var_dump(array_rsort($test3));
var_dump(array_rsort($test3,true));
?>