逆序二维数组插入一元素的php代码_PHP
程序员文章站
2022-05-13 22:21:30
...
复制代码 代码如下:
/**
* 逆序二维数组插入一元素
*
* @author WadeYu
* @date 2012-05-30
*/
$aSorted = array(
array(1, 100),
array(2, 90),
array(3, 80),
array(4, 70),
array(5, 60),
array(6, 50),
array(7, 40),
array(8, 40),
array(9, 40),
array(10, 20),
);
$aInsert = array(11, 40);
$maxCmpIdx = 0;
$cnt = 0;
$maxCnt = 10;
foreach ($aSorted as $idx => $arr){
if ($arr[0] == $aInsert[0]){
$maxCmpIdx = $idx;
}
$cnt++;
}
if ( !$maxCmpIdx){
$maxCmpIdx = $cnt++;
}
$aSorted[$maxCmpIdx] = $aInsert;
for ($i = $maxCmpIdx; $i > 0; $i--){
if ($aSorted[$i][1] > $aSorted[$i-1][1]){
$aTmp = $aSorted[$i-1];
$aSorted[$i-1] = $aSorted[$i];
$aSorted[$i] = $aTmp;
continue ;
}
break;
}
for ($i = $cnt; $i > $maxCnt; $i--){
unset($aSorted[$i-1]);
}
print_r($aSorted);
/**
* 逆序二维数组插入一元素
*
* @author WadeYu
* @date 2012-05-30
*/
$aSorted = array(
array(1, 100),
array(2, 90),
array(3, 80),
array(4, 70),
array(5, 60),
array(6, 50),
array(7, 40),
array(8, 40),
array(9, 40),
array(10, 20),
);
$aInsert = array(11, 40);
$maxCmpIdx = 0;
$cnt = 0;
$maxCnt = 10;
foreach ($aSorted as $idx => $arr){
if ($arr[0] == $aInsert[0]){
$maxCmpIdx = $idx;
}
$cnt++;
}
if ( !$maxCmpIdx){
$maxCmpIdx = $cnt++;
}
$aSorted[$maxCmpIdx] = $aInsert;
for ($i = $maxCmpIdx; $i > 0; $i--){
if ($aSorted[$i][1] > $aSorted[$i-1][1]){
$aTmp = $aSorted[$i-1];
$aSorted[$i-1] = $aSorted[$i];
$aSorted[$i] = $aTmp;
continue ;
}
break;
}
for ($i = $cnt; $i > $maxCnt; $i--){
unset($aSorted[$i-1]);
}
print_r($aSorted);