Php advanced operations for traversing arrays _ PHP Tutorial

Source: Internet
Author: User
Php advanced operations for traversing arrays. In php, list, foreach, and each are usually used to traverse data, but the following tutorial may not be used. next I will introduce you to advanced instances for traversing arrays, it is expected that list, foreach, and each will be used for traversing data in php, but the following tutorial may not be used. next I will introduce you to advanced instances for traversing arrays separately, I hope this method will be helpful to you.

When learning programming languages, I always learn for, and then try to use while to write some exercises for the effect.

Before foreach is available, what should I do if I want the foreach function? Write (using while, list, and each ).


In this article, we can see the foreach method of PHP.

The code is as follows:

// Old statement
Reset ($ attributes );
While (list ($ key, $ value) = each ($ attributes )){
// Do something
}

// Added PHP4
Foreach ($ attributes as $ key => $ value ){
// Do something
}

Multi-dimensional join array sorting
PHP provides some array sorting functions, such as sort (), ksort (), and asort (), but does not provide sorting for multi-dimensional joined arrays.


For example, the following array:

The code is as follows:

Array
(
[0] => Array
(
[Name] => chess
[Price] = & gt; 12.99
)

[1] => Array
(
[Name] => checkers
[Price] = & gt; 9.99
)

[2] => Array
(
[Name] => backgammon
[Price] = & gt; 29.99
)
)

To sort the array in ascending order, you need to write a function to compare the price, and then pass the function as a callback function to the usort () function to implement this function:

The code is as follows:

Function comparePrice ($ priceA, $ priceB ){
Return $ priceA ['price']-$ priceB ['price'];
}

Usort ($ games, 'companyprice'); after the program fragment is executed, the array will be sorted. The result is as follows:

Array
(
[0] => Array
(
[Name] => checkers
[Price] = & gt; 9.99
)

[1] => Array
(
[Name] => chess
[Price] = & gt; 12.99
)

[2] => Array
(
[Name] => backgammon
[Price] = & gt; 29.99
)
)

Sort the array in descending order and change the positions of the two subtraction values in the comparePrice () function.

Traverse arrays in reverse order
PHP's While loop and For loop are the most common methods to traverse an array. But how do you traverse the following array?

The code is as follows:

Array
(
[0] => Array
(
[Name] => Board
[Games] => Array
(
[0] => Array
(
[Name] => chess
[Price] = & gt; 12.99
)

[1] => Array
(
[Name] => checkers
[Price] = & gt; 9.99
)
)
)
)

The PHP Standard Library has an iterators class for the set, which is not only used to traverse some heterogeneous data structures (such as file systems and database query result sets ), you can also traverse nested arrays with unknown sizes. For example, you can use the RecursiveArrayIterator iterator to traverse the preceding array:

The code is as follows:

$ Iterator = new RecursiveArrayIterator ($ games );
Iterator_apply ($ iterator, 'navigateearray', array ($ iterator ));

Function navigateArray ($ iterator ){
While ($ iterator-> valid ()){
If ($ iterator-> hasChildren ()){
NavigateArray ($ iterator-> getChildren ());
} Else {
Printf ("% s: % s", $ iterator-> key (), $ iterator-> current ());
}
$ Iterator-> next ();
}
}

The following result is displayed when the code is executed:

Name: Board
Name: chess
Price: 12.99
Name: checkers
Price: 9.99

Filter join array results
Suppose you get an array like the next one, but you just want to operate the element with a price lower than $11.99:

The code is as follows:

Array
(
[0] => Array
(
[Name] => checkers
[Price] = & gt; 9.99
)

[1] => Array
(
[Name] => chess
[Price] = & gt; 12.99
)

[2] => Array
(
[Name] => backgammon
[Price] = & gt; 29.99
)
)

Using the array_reduce () function can be easily implemented:

The code is as follows:

Function filterGames ($ game ){
Return ($ game ['price'] <11.99 );
}

$ Names = array_filter ($ games, 'filtergames ');

The array_reduce () function filters out all elements that do not meet the callback function. In this example, the callback function is filterGames. Any element with a price lower than 11.99 will be left behind, and others will be removed. Execution result of the code segment:

The code is as follows:
Array
(
[1] => Array
(
[Name] => checkers
[Price] = & gt; 9.99
)
)

Convert objects into arrays
One requirement is to convert an object into an array. the method is much simpler than you think. only forced conversion is enough! Example:

The code is as follows:

Class Game {
Public $ name;
Public $ price;
}

$ Game = new Game ();
$ Game-> name = 'Chess ';
$ Game-> price = 12.99;

Print_r (array ($ game); execute this example to generate the following results:

Array
(
[0] => Game Object
(
[Name] => chess
[Price] = & gt; 12.99
)
)

Converting an object into an array may lead to unpredictable side effects. For example, in the code snippet above, all member variables are of the public type, but the returned results for private variables are different. The following is another example:

The code is as follows:

Class Game {
Public $ name;
Private $ _ price;

Public function setPrice ($ price ){
$ This-> _ price = $ price;
}
}

$ Game = new Game ();
$ Game-> name = 'Chess ';
$ Game-> setPrice (12.99 );

Print_r (array ($ game); execute this code snippet:

Array
(
[0] => Game Object
(
[Name] => chess
[_ Price: Game: private] = & gt; 12.99
)
)

As you can see, for differentiation, the key of the private variable stored in the array is automatically changed.

"Natural sorting" of arrays"
PHP is not sure about the sorting result of the "letter and digit" string. For example, assume that you have many image names stored in the array:

The code is as follows:
$ Arr = array (
0 => 'madden2011.png ',
1 => 'madden2011-1.png ',
2 => 'madden2011-2.png ',
3 => 'madden2012.png'
);

How do you sort the array? If you use sort () to sort the array, the result is as follows:

The code is as follows:
Array
(
Madden2011-1.png
Madden2011-2.png
[2] => madden2011.png
[3] => madden2012.png
)

Sometimes this is what we want, but what should we do if we want to keep the original subscript? To solve this problem, you can use the natsort () function, which sorts arrays in a natural way:

The code is as follows:

$ Arr = array (
0 => 'madden2011.png ',
1 => 'madden2011-1.png ',
2 => 'madden2011-2.png ',
3 => 'madden2012.png'
);

Natsort ($ arr );
Echo"

"; print_r($arr); echo "
";
?>

Running result:

Array
(
Madden2011-1.png
Madden2011-2.png
[0] => madden2011.png
[3] => madden2012.png
)

...

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.