Home > Article > Backend Development > Advanced traversal and operation processing methods of PHP array_PHP tutorial
I have talked about simple array traversal before, which is based on statements such as foreach and for. Now I will introduce the advanced traversal method of array. Friends can refer to it. These arrays are really useful for development, with strong practical performance and complex It's also higher.
PHP’s handling of arrays can be called one of the most attractive features of the language. It supports more than 70 array-related functions. Whether you want to flip an array, determine whether a value exists in an array, convert an array to a string, or calculate the size of an array, you can do it simply by executing an existing function. However, there are also some array-related tasks that have higher requirements for developers. Just knowing a certain function in the manual cannot solve it. These tasks require some in-depth understanding of the original features of PHP and some imagination to solve the problem. force.
Multidimensional associative array sorting
PHP provides some array sorting functions, such as sort(), ksort(), and asort(), but it does not provide sorting of multi-dimensional associative arrays.
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 yourself to compare prices, and then pass the function as a callback function to the usort() function to implement this function:
The code is as follows | Copy code | ||||
|
After executing this program fragment, the array will be 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, just swap the positions of the two subtracted numbers in the comparePrice() function.
Traverse the array in reverse order
PHP’s While Loop and For Loop are the most commonly used methods to traverse an array. But how do you iterate over an array like the one below?
Array
(
[0] => Array
(
[name] => Board
[games] => Array
(
[0] =>
(
[name] => chess
[price] =>
)
[1] => Array
[Name] = & gt; checker
[price] => 9.99
)
)
)
)
There is an iterator class for collections in the PHP standard library. It can not only be used to traverse some heterogeneous data structures (such as file systems and database query result sets), but can also be used to iterate some embedded objects of unknown size. Traversal of arrays. For example, to traverse the above array, you can use the RecursiveArrayIterator iterator:
The code is as follows | Copy code | ||||
$iterator = new RecursiveArrayIterator($games); iterator_apply($iterator, 'navigateArray', array($iterator));
|
Executing this 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 are given the following array, but you only want to operate on elements whose price is less than $11.99:
Array
(
[0] => Array
(
[name] => checkers
[price] => 9.99
)
[1] => Array
(
[name] => chess
[price] => 12.99
)
[2] => Array
(
[name] => backgammon
[price] => 29.99
)
)
It can be easily implemented using the array_reduce() function:
The code is as follows | Copy code | ||||
return ($game['price'] < 11.99); }
|
[name] => checkers
[price] => 9.99
)
)
代码如下 | 复制代码 |
class Game { $game = new Game(); print_r(array($game)); 执行该例子就会产生如下结果: Array |
Convert object to array
代码如下 | 复制代码 |
class Game { public function setPrice($price) { $game = new Game(); print_r(array($game));执行该代码片段: Array |
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 produce the following results: Array ( [0] => Game Object ( [name] => chess [price] => 12.99 ) ) |
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 this code snippet: Array ( [0] => Game Object ( [name] => chess [_price:Game:private] => 12.99 ) ) |
As you can see, in order to distinguish, the keys of the private variables saved in the array are automatically changed.
“Natural ordering” of arrays
PHP’s sorting results for “alphanumeric” strings are undefined. For example, suppose you have many image names stored in an array:
The code is as follows | Copy code | ||||||||||||
0=>'madden2011.png', 1=>'madden2011-1.png',
3=>'madden2012.png'
);
|
The code is as follows | Copy code |
$arr = array(<🎜>
0=>'madden2011.png',
1=>'madden2011-1.png',
2=>'madden2011-2.png',
3=>'madden2012.png'
);
natsort($arr);
echo ""; print_r($arr); echo ""; ?> Run result: Array ( [1] => madden2011-1.png [2] => madden2011-2.png [0] => madden2011.png [3] => madden2012.png ) |
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 of the above code is as follows:
Array ( [A] => 2 [B] => 2 [C] => 2 [D] => 2 )
As you can see, the values corresponding to each key in $array have been modified to 2. It seems this approach actually works.
Use key values to operate the elements of the array
Sometimes, the array may represent some interrelated elements. If you encounter one of these interrelated elements and mark other elements, the above reference will definitely not work. At this time, when modifying these associated elements, you must use their corresponding key values. Try it first and see if it works:
The code is as follows | Copy code | ||||||||||||
If($key == "B"){
echo '
If($value === "CHANGE") echo $value.'';
|
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); ?> |
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 ) |
Then it is indeed 1.
What is the reason for this? Turning to the foreach page of the PHP document, I suddenly realized:
Note: Unless the array is referenced, foreach operates on a copy of the specified array, not the array itself. foreach has some side effects on array pointers. Do not rely on the value of an array pointer during or after a foreach loop unless it is reset.
It turns out that foreach operates on a copy of the specified array. No wonder, getting $value doesn’t work! After understanding this, the above problem is solved. As long as in foreach, you can directly take the elements in $array according to the key and perform various judgment and assignment operations.
Summary and extension
PHP's array traversal and operation capabilities are indeed very powerful, but the solutions to some slightly more complex problems are not so obvious. In fact, this is the case in any field. A language and grammar provide basic operations. Solutions to complex problems require developers’ own thinking, imagination and code writing.