作者kevin0523 (Kevin)
看板PHP
標題[請益] 關聯性陣列排序問題
時間Thu Apr 19 11:25:51 2007
關聯性陣列排序問題
Given an array in
PHP : $ list = array('apple'=>300, 'orange'=>150, 'banana'=>100,
'mango'=>330);
sort the array by the order of key and value respectively with your own
sorting algorithm.
Please don't use the sorting functions provided by language.
請問各位高手該如何寫出來呢? 不能使用ksort,rsort,等 php內建sort函式
想破頭了 想不出來
若不是關聯性陣列可使用氣泡排序 可是關聯性我就寫不出來了,有人可以幫幫忙嗎?感謝
~
$a = array(2,30,1,75,65,32,24,19,3,60,51) ;
$ln = count($a ) ;
for ($i = 0 ; $i <$ln; $i++) {
echo $a[$i] . "," ;
}
echo "<br>" ;
//氣泡排序-------------------------------------------------------------------
echo "氣泡排序<br>" ;
for ($j= $ln ; $j>1 ; $j--) {
for ($i= 0 ; $i< $j-1 ; $i++) {
if ($a[$i]>$a[$i+1]) {
//echo $a[$i] ."--". $a[$i+1] ."<br>" ;
$temp = $a[$i+1] ;
$a[$i+1] = $a[$i];
$a[$i]= $temp ;
//echo $a[$i] . " , " . $a[$i+1] . " <br>" ;
}
}
}
for ($i = 0 ; $i <$ln; $i++) {
echo $a[$i] . "," ;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 59.105.128.151
1F:推 foxzgerald:這是要分別對 key 和 value 排序嘛? 04/20 01:46