'哈哈', 'sex' => '男' ], [ 'name' => '李四', 'sex' => '男' ], [ 'name' => '王五', 'sex' => '男' ], [ 'name' => '张三1', 'sex' => '男' ], [ 'name' => '李四', 'sex' => '女' ], ]; /* * $dataArr array 要排序数组 * $whereArr array 排序的条件 * $key string 要排序数组的排序条件字段 * return array */ function SortAry($dataArr = [], $whereArr = [], $key = ''){ $returnArr = []; if(empty($dataArr) || empty($whereArr) || empty($key) ) { $returnArr['error'] = '参数必须'; return $returnArr; } if(!is_array($dataArr)) { $returnArr['error'] = '第一个参数 $dataArr必须是数组'; return $returnArr; } if(!is_array($whereArr)) { $returnArr['error'] = '第二个参数 $whereArr必须是数组'; return $returnArr; } if(!is_string($key)) { $returnArr['error'] = '第三个参数 $key必须是字符串'; return $returnArr; } $newArr = []; $newReArr = []; foreach($dataArr as $dKey => $dVal){ //不是二维跳过 if(!is_array($dVal)) { $newReArr[] = $dVal; continue; } //判断条件字段是否设置 if(!isset($dVal[$key])) { $newReArr[] = $dVal; continue; } //不在排序条件中 if(!in_array($dVal[$key], $whereArr)) { $newReArr[] = $dVal; continue; } $newArr[$dVal[$key]][] = $dVal; } if($newArr) { foreach($whereArr as $wKey => $wVal){ //判断条件字段是否设置 if(isset($newArr[$wVal])){ foreach($newArr[$wVal] as $nKey => $nVal){ $returnArr[] = $nVal; } } } } $returnArr = array_merge($returnArr, $newReArr); return $returnArr; } $reData = SortAry($dataArr, $whereArr, '-1'); if(isset($reData['error'])) { echo $reData['error']; } else { var_dump($reData); }