Insert an element into the array in php code _ PHP Tutorial

Source: Internet
Author: User
Insert an element program code into the array in php. 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: Copy the code? In this article, php 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.

Bytes. The code is as follows? Php...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.