This article is a sorted two-dimensional data. we need to insert an element into the array, which needs to be sorted after being saved to the data. the code is as follows: & lt ;? Php *** two-dimensional array in reverse order
This article is a sorted two-dimensional data. we need to insert an element into the array, which needs to be sorted after being saved to the data. the code is as follows:
-
- /**
- * Insert an element into a two-dimensional array in reverse order
- *
- * @ Author WadeYu
- * @ Date 2012-05-30
- */
- $ ASorted = array (
- Arrays (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. here we only introduce one method. if you need to know more, you can search on this site.