Advanced traversal and operation processing methods of PHP array_PHP tutorial

WBOY
Release: 2016-07-13 16:57:45
Original
916 people have browsed it

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
 代码如下 复制代码

function comparePrice($priceA, $priceB){
    return $priceA['price'] - $priceB['price'];
}

usort($games, 'comparePrice');

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

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));
 代码如下 复制代码

$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();
 } 
}

function navigateArray($iterator) { while ($iterator->valid()) { if ($iterator->hasChildren()) { NavigateArray($iterator->getChildren()); } else { Printf("%s: %s", $iterator->key(), $iterator->current()); } $iterator->next(); } }

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
 代码如下 复制代码

function filterGames($game){
 return ($game['price'] < 11.99);
}

$names = array_filter($games, 'filterGames');

function filterGames($game){

return ($game['price'] < 11.99);

}


$names = array_filter($games, 'filterGames');


The array_reduce() function will filter out all elements that do not satisfy the callback function. The callback function in this example is filterGames. Any element with a price lower than 11.99 will be kept, and the others will be eliminated. The execution result of this code segment:

Array
(
[1] => Array

(

[name] => checkers [price] => 9.99
)
)

 代码如下 复制代码

class Game {
 public $name;
 public $price;
}

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

print_r(array($game));

执行该例子就会产生如下结果:

Array
(
[0] => Game Object
  (
    [name] => chess
    [price] => 12.99
  )
)

Convert object to array

 代码如下 复制代码

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));执行该代码片段:

Array
(
[0] => Game Object
  (
    [name] => chess
    [_price:Game:private] => 12.99
  )
)

One requirement is to convert the object into an array form. The method is much simpler than you think, just force conversion is enough! 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 produce the following results: Array ( [0] => Game Object ( [name] => chess [price] => 12.99 ) )
Converting objects to arrays can have some unpredictable side effects. For example, in the above code snippet, all member variables are of public type, but the return results for private variables will be 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 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
 代码如下 复制代码

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

你怎样对这个数组进行排序呢?如果你用sort()对该数组排序,结果是这样的:

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

$arr = array(

0=>'madden2011.png',

1=>'madden2011-1.png',
 代码如下 复制代码

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

natsort($arr);
echo "

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

运行结果:

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

2=>'madden2011-2.png',

3=>'madden2012.png' );
How do you sort this array? If you use sort() to sort the array, the result is like this:

Array
 代码如下 复制代码

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

( [0] => madden2011-1.png [1] => madden2011-2.png [2] => madden2011.png [3] => madden2012.png )
Sometimes this is what we want, but what if we want to keep the original subscript? To solve this problem, you can use the natsort() function, which sorts the array in a natural way:
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 )
Value changing operation during traversal Reference Operator& Look at the $array array in the code below. Use the reference operator on $value during the foreach loop. In this way, when the value of $value is modified in the loop, the corresponding element value in $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 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
 代码如下 复制代码

$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);
?>

$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 '
';

}
 代码如下 复制代码

$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);
?>

If($value === "CHANGE")

echo $value.'
';
 代码如下 复制代码
Array ( [A] => CHANGE [B] => 1 [C] => 1 [D] => CHANGE )
1
Array ( [A] => CHANGE [B] => 1 [C] => 1 [D] => CHANGE )
} print_r($array); ?>
Don’t worry about looking at the output, what should we imagine it should be like? Print the modified array, print a "CHANGE", and print the modified array again. Is it right? Let’s take a look at the output! Array ( [A] => CHANGE [B] => 1 [C] => 1 [D] => CHANGE ) Array ( [A] => CHANGE [B] => 1 [C] => 1 [D] => CHANGE ) Huh? What's going on? Where has our CHANGE gone? According to our idea, since $array has changed, when traversing to the element with the key value "D", its new value "CHANGE" should be output! But the reality is not what we think. What did PHP do here? Modify the above code slightly. Since "D" => CHANGE is correct when printing an array, let's modify the judgment condition of the second if statement:
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 will definitely not be equal to "CHANGE"! Is it equal to 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 )

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.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/631503.htmlTechArticleI talked about simple array traversal earlier, which is based on statements such as foreach and for. Now I will introduce arrays Introduction to the advanced traversal method, friends can refer to it, these arrays are really used to open...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!