problem in sorting 2-d array sort
I m facing problem in sorting this 2-d array on the basis of key eg(33 in the sample code) so the output will look like 7,7,28,33,35,38.Here is the sample code.
thanks in advance
<?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 == 开发者_如何学Python0)
$str=$arrnew[$key];
if($str < $arrnew[$key])
//$arrnew[$key]=$val;
//echo $key."<BR>";
}
}
print_r($arrnew);
$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);
If each subarray only has one key-value-pair, you can create a new array from it:
// 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));
that's it. Enjoy!
精彩评论