PHP代码如下:
1
2 /**
3 * 逆序二维数组插入一元素
4 *
5 * @author WadeYu
6 * @date 2012-05-30
7 */
8 $aSorted = array(
9 array(1, 100),
10 array(2, 90),
11 array(3, 80),
12 array(4, 70),
13 array(5, 60),
14 array(6, 50),
15 array(7, 40),
16 array(8, 40),
17 array(9, 40),
18 array(10, 20),
19 );
20 $aInsert = array(11, 40);
21 $maxCmpIdx = 0;
22 $cnt = 0;
23 $maxCnt = 10;
24 foreach ($aSorted as $idx => $arr){
25 if ($arr[0] == $aInsert[0]){
26 $maxCmpIdx = $idx;
27 }
28 $cnt++;
29 }
30 if ( !$maxCmpIdx){
31 $maxCmpIdx = $cnt++;
32 }
33 $aSorted[$maxCmpIdx] = $aInsert;
34 for ($i = $maxCmpIdx; $i > 0; $i--){
35 if ($aSorted[$i][1] > $aSorted[$i-1][1]){
36 $aTmp = $aSorted[$i-1];
37 $aSorted[$i-1] = $aSorted[$i];
38 $aSorted[$i] = $aTmp;
39 continue ;
40 }
41 break;
42 }
43 for ($i = $cnt; $i > $maxCnt; $i--){
44 unset($aSorted[$i-1]);
45 }
46 print_r($aSorted);
摘自 huan & ping