Advanced traversal and manipulation methods for PHP Arrays _php Tutorial

Source: Internet
Author: User
Before I talked about simple array traversal, these are based on statements such as Foreach,for, I would like to introduce the advanced traversal method of the array introduction, friends can refer to, these arrays are really used in the development of practical can be strong, complex and higher.

The processing of an array of PHP can be called one of the most attractive features of the language, and it supports more than 70 array-related functions. Whether you want to flip an array, determine if a value exists in an array, convert an array to a string, or calculate the size of an array, you can do it just by executing an existing function. However, there are some array-related tasks that are more demanding to the developer, just knowing that the manual has a function that cannot be solved, these tasks need to have some in-depth understanding of the original PHP features, but also need some imagination to solve the problem.

Multidimensional associative array Ordering
PHP provides some functions for sorting arrays, such as sort (), Ksort (), and Asort (), but does not provide a sort of multidimensional associative array.


For example, an array like this:

Array
(
[0] = = Array
(
[Name] = Chess
[Price] = 12.99
)

[1] = = Array
(
[Name] = Checkers
[Price] = 9.99
)

[2] = = Array
(
[Name] = Backgammon
[Price] = 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 accomplish this:

The code is as follows Copy Code

function Compareprice ($priceA, $priceB) {
return $priceA [' Price ']-$priceB [' Price '];
}

Usort ($games, ' compareprice ');

When the program fragment is executed, the array is sorted and the result is as follows:

Array
(
[0] = = Array
(
[Name] = Checkers
[Price] = 9.99
)

[1] = = Array
(
[Name] = Chess
[Price] = 12.99
)

[2] = = Array
(
[Name] = Backgammon
[Price] = 29.99
)
)

To sort the array in descending order, replace the two minus number in the Compareprice () function with the position.

Iterating through arrays in reverse order
PHP's while loop and for loop are the most common methods of traversing an array. But how do you traverse the array like this one?

Array
(
[0] = = Array
(
[Name] = Board
[Games] = = Array
(
[0] = = Array
(
[Name] = Chess
[Price] = 12.99
)

[1] = = Array
(
[Name] = Checkers
[Price] = 9.99
)
)
)
)

The PHP standard library has an iterator to the collection Iterators class that can be used not only to traverse some heterogeneous data structures (such as file systems and database query result sets), but also to traverse a number of nested arrays that do not know the size. For example, the traversal of the above array can be done using the Recursivearrayiterator iterator:

The code is as follows Copy Code

$iterator = new Recursivearrayiterator ($games);
Iterator_apply ($iterator, ' Navigatearray ', Array ($iterator));

function Navigatearray ($iterator) {
while ($iterator->valid ()) {
if ($iterator->haschildren ()) {
Navigatearray ($iterator->getchildren ());
} else {
printf ("%s:%s", $iterator->key (), $iterator->current ());
}
$iterator->next ();
}
}

Executing the code will give the following results:

Name:board
Name:chess
price:12.99
Name:checkers
price:9.99

Filter the results of associative arrays
Suppose you get an array of the following, but you just want to manipulate the element with a price below $11.99:

Array
(
[0] = = Array
(
[Name] = Checkers
[Price] = 9.99
)

[1] = = Array
(
[Name] = Chess
[Price] = 12.99
)

[2] = = Array
(
[Name] = Backgammon
[Price] = 29.99
)
)

Using the Array_reduce () function can be a simple implementation:

The code is as follows Copy Code

function Filtergames ($game) {
Return ($game [' Price '] < 11.99);
}

$names = Array_filter ($games, ' filtergames ');

The Array_reduce () function filters out all elements that do not satisfy the callback function, and the callback function for this example is filtergames. Any element with a price below 11.99 will be left and the others will be removed. The result of the code snippet execution:

Array
(
[1] = = Array
(
[Name] = Checkers
[Price] = 9.99
)
)

Object conversions to an array
A requirement is to convert an object into an array form, which is much simpler than you think, and just casts it! Example:

The code is as follows Copy Code

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

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

Print_r (Array ($game));

Executing this example will result in the following:

Array
(
[0] = = Game Object
(
[Name] = Chess
[Price] = 12.99
)
)

There are some unexpected side effects of converting an object to an array. For example, the above code snippet, all member variables are of the public type, but the return result for private variables will become different. Here is another example:

The code is as follows Copy Code

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 the code snippet:

Array
(
[0] = = Game Object
(
[Name] = Chess
[_price:game:private] = 12.99
)
)

As you can see, the keys to the private variables stored in the array are automatically changed for the sake of distinction.

The "natural sort" of an array
PHP's ordering of "alpha-numeric" strings is indeterminate. For example, suppose you have a lot of picture names stored in an array:

The code is as follows Copy Code

$arr = Array (
0=> ' Madden2011.png ',
1=> ' Madden2011-1.png ',
2=> ' Madden2011-2.png ',
3=> ' Madden2012.png '
);

How do you sort this array? If you sort the array with sort (), the result is this:

Array
(
[0] = Madden2011-1.png
[1] = Madden2011-2.png
[2] = Madden2011.png
[3] = Madden2012.png
)

Sometimes that's what we want, but what if we want to keep the original subscript? To resolve the problem, you can use the Natsort () function, which sorts the array in a natural way:

copy code

"!--? php
$arr = Array (
0=> ' mad Den2011.png ',
1=> ' madden2011-1.png ',
2=> ' madden2011-2.png ',
3=> ' madden2012.png '
);

Natsort ($arr);
Echo

"; 
?

Run Result:

Array
(
[1] = Madden2011-1.png
[2] = Madden2011-2.png
[0] = = Madden2011.png
[3] = Madden2012.png
)

The change operation during traversal
Reference Operators &
Look at the $array array in the following code, using the reference operator for $value in the Foreach loop, so that when the value of $value is modified in the loop, the corresponding element value in the $array is modified.

The code is as follows Copy Code

$array = Array ("A" =>1, "B" =>1, "C" =>1, "D" =>1);
foreach ($array as & $value)
$value = 2;
Print_r ($array);
?>

The output from the previous section of the code is as follows:

Array ([A] = 2 [B] = 2 [C] = 2 [D] = 2)
You can see that the values for each key in the $array have been modified to 2. It seems that this approach really works.

Manipulating elements of an array using key values
Sometimes, the array may represent some interrelated elements, and if one of these interrelated elements is encountered, the other elements will be labeled, and the references above must be useless. When modifying these associated elements, it is necessary to use their corresponding key values. Try it first. No:

The code is as follows Copy Code

$array = Array ("A" =>1, "B" =>1, "C" =>1, "D" =>1);
foreach ($array as $key = = $value) {
if ($key = = "B") {
$array ["A"] = "change";
$array ["D"] = "change";
Print_r ($array);
Echo '
';
}

if ($value = = = "Change")
echo $value. '
';
}
Print_r ($array);
?>

Don't worry about the output, what should we imagine? Print the modified array, print a "change", and then print the modified array again. Is that right? Let's look at the output!

Array ([A] = change [B] = 1 [C] = 1 [D] = change)
Array ([A] = change [B] = 1 [C] = 1 [D] = change)
Hey? What's the situation? Where's our change?

According to our idea, since $array has changed, then when traversing to an element with a key value of "D", it should output its new value "Change"! But the truth is not what we think. What is PHP doing here? Make a slight change to the above code. Now that the array is printed, the "D" =>change is correct, then we modify the second if statement to determine the condition:

The code is as follows Copy Code

$array = Array ("A" =>1, "B" =>1, "C" =>1, "D" =>1);
foreach ($array as $key = = $value) {
if ($key = = "B") {
$array ["A"] = "change";
$array ["D"] = "change";
Print_r ($array);
Echo '
';
}

if ($array [$key] = = = "Change")
echo $value. '
';
}
Print_r ($array);
?>

Guess what it will output? $value must not be equal to "change"! Does it mean 1?

The code is as follows Copy Code
Array ([A] = change [B] = 1 [C] = 1 [D] = change)
1
Array ([A] = change [B] = 1 [C] = 1 [D] = change)

Well, it really is 1.

What is the reason for God's horse? Turn to the foreach page of the PHP document and suddenly:

Note: Unless the array is referenced, foreach operates on a copy of the specified array, not the array itself. The foreach array pointer has some side effects. Unless you reset it, do not rely on the value of the array pointer in the Foreach loop or after the loop.

The original foreach operation is a copy of the specified array. No wonder, taking $value is useless! Understanding here, the above problem is solved. As long as in the foreach, directly follow the key to take the elements of the $array in a variety of judgment assignment operation is OK.


Summary and extension
PHP's array traversal and manipulation capabilities are really powerful, but the solution to some of the more complex problems is not so obvious. This is true in any field, where a language and grammar provide basic operations, and solutions to complex problems require the developer's own thinking, imagination, and code writing to complete.

http://www.bkjia.com/PHPjc/631503.html www.bkjia.com true http://www.bkjia.com/PHPjc/631503.html techarticle before I talked about simple array traversal, these are based on statements such as Foreach,for, I would like to introduce the advanced traversal method of the array, friends can refer to, these arrays are really used to open ...

  • 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.