This article is a sorted two-dimensional data. We need to insert an element into the array. This needs to be sorted after saving it to the data.
The code is as follows
代码如下 |
复制代码 |
/**
* 逆序二维数组插入一元素
*
* @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);
|
|
Copy code
|
|
/**
* Insert an element into a two-dimensional array in reverse order
*
* @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);
There are many ways to insert elements into an array. Only one is introduced here. Friends who need to know more can search on this site.
http://www.bkjia.com/PHPjc/631617.htmlwww.bkjia.comtrue
http: //www.bkjia.com/PHPjc/631617.htmlThis article is a sorted two-dimensional data. We want to insert an element into the array and save it to The data still needs to be sorted. The code is as follows Copy the code ?php...