排序二维数组排序的问题

时间:2010-09-20 14:36:28

标签: php

我在基于密钥例如(示例代码中的33)对这个二维数组进行排序时遇到问题 所以输出看起来像7,7,28,33,35,38。这是示例代码。

提前致谢

<?php
$arr=array ( 0 => array ( 33 => 'SY2', ), 1 => array ( 38 => 'PR25', ), 2 => array ( 7 => 'SK22', ), 3 => array ( 7 => 'BT1', ), 4 => array ( 28 => 'WN8', ), 5 => array ( 35 => 'ST21', ));
print_r($arr);
$arrnew=array();
$str=0;
for($j=0;$j<count($arr);$j++){
 foreach($arr[$j] as $key=>$val){
  if($str == 0)
   $str=$arrnew[$key];
  if($str < $arrnew[$key])

  //$arrnew[$key]=$val;
  //echo $key."<BR>";
 }
}

print_r($arrnew);

2 个答案:

答案 0 :(得分:0)

如果每个子数组只有一个键值对,则可以从中创建一个新数组:

// copy data from $arr to $newArray:
$newArray = array();
foreach($arr as $v)
    $newArray[array_keys($v)[0]] = $v[0];

// sort newArray:
ksort($newArray)

// if you want to, you can copy it back:
$arr = array();
foreach($newArray as $k => $v)
    array_push($arr, array($k, $v));

就是这样。享受!

答案 1 :(得分:0)

$arr=array ( 0 => array ( 33 => 'SY2', ), 1 => array ( 38 => 'PR25', ), 2 => array ( 7 => 'SK22', ), 3 => array ( 7 => 'BT1', ), 4 => array ( 28 => 'WN8', ), 5 => array ( 35 => 'ST21', ));
foreach($arr as $key => $val)
{
 foreach ($val as $key2 => $val2)
 {
  $sort[$key] = $key2;
 }
}
array_multisort($sort, SORT_ASC, $arr);
print_r($arr);