search
HomeBackend DevelopmentPHP TutorialAdvanced traversal and operation processing methods of PHP array_PHP tutorial

Advanced traversal and operation processing methods of PHP array_PHP tutorial

Jul 13, 2016 pm 04:57 PM
fforeachphpandbased ondeal withIoperatearraymethodofSimpleTraverseadvanced

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'] }

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

function filterGames($game){

return ($game['price'] }


$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...
Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function