Home Backend Development PHP Tutorial PHP:数组操作函数array_walk()和array_map()

PHP:数组操作函数array_walk()和array_map()

Jun 20, 2016 pm 12:37 PM

 array_map()的函数原型为:array array_map ( callback callback, array arr1 [, array...] )

 array_map() 返回一个数组,该数组包含了arr1中的所有单元经过callback作用过之后的单元。callback接受的参数数目应该和传递给 array_map() 函数的数组数目一致。

  

  callback函数就是array_map所将调用来处理元素单元函数,应以字符串的形式将函数名传递给array_map()

  如:(php官方手册所给出的代码)

                    function cube($n)
            {
                return($n * $n *$n);
            }

            $a = array(1,2, 3, 4, 5);
            $b= array_map("cube",$a);
            print_r($b);
        ?>

    cube即为callback函数 ,且array_map的callback函数的参数每一个应均为数组的元素,也就是array_map()除了第一个参数外,其余参数应均为数组且应与回调函数的参数个数一样.

    

<?php	//callback 1	function  check($n)	{		//array_mapcallback的参数为数组的元素,		//也就是callback中有几个参数array_map就应传入几个数组		if($n>100)		{			return  $n-10;		}else 		{			return  $n;		}	}	//callback 2	function  add($a,$b)	{		return  $a+$b;	}		$arr = array(101,85,35,105,99,109);//	var_dump($arr);	$brr = array(1,2,3,4,5,6);	$arr = array_map("check", $arr);	$brr = array_map("add", $arr,$brr);			print_r($arr);	echo "<br/>";	print_r($brr);		?>
Copy after login

输出结果

array (size=6)  0 => int 101  1 => int 85  2 => int 35  3 => int 105  4 => int 99  5 => int 109
Copy after login

Array ( [0] => 91 [1] => 85 [2] => 35 [3] => 95 [4] => 99 [5] => 99 )
Array ( [0] => 92 [1] => 87 [2] => 38 [3] => 99 [4] => 104 [5] => 105 )

========================================================================================

我是分割线

========================================================================================


与array_map()不同array_walk()的返回值是布尔型,也就是如果想要修改数组的数据,应该在callback函数上做手脚(也就是引用)

array_walk()会将数组的元素的值,以及键值传递给callback函数,此外还允许传递其类型的数据给callback函数.

以下为其原型以及官方文档:

bool array_walk ( array &array, callback funcname [,mixed userdata] )

如果成功则返回 TRUE,失败则返回 FALSE

将用户自定义函数funcname应用到array数组中的每个单元。典型情况下funcname接受两个参数。array参数的值作为第一个,键名作为第二个。如果提供了可选参数userdata,将被作为第三个参数传递给 callbackfuncname。

如果funcname函数需要的参数比给出的多,则每次 array_walk() 调用funcname时都会产生一个E_WARNING 级的错误。这些警告可以通过在 array_walk() 调用前加上 PHP 的错误操作符 @ 来抑制,或者用 error_reporting()

注: 如果funcname需要直接作用于数组中的值,则给funcname的第一个参数指定为引用。这样任何对这些单元的改变也将会改变原始数组本身。

注: 将键名和 userdata 传递到funcname中是 PHP 4.0新增加的。

array_walk() 不会受到array内部数组指针的影响。array_walk() 会遍历整个数组而不管指针的位置。

用户不应在回调函数中改变该数组本身。例如增加/删除单元,unset 单元等等。如果 array_walk() 作用的数组改变了,则此函数的的行为未经定义,且不可预期。

以下是我自己写的一个简单的例子:

<?php	function alter(&$value,$key,$userdata)	{	        //在此处不对元素值做任何修改,如果想要修改则需像我一样给参数加上引用		echo $key.$userdata.$value.'<br/>';	}	$arr = array("a"=>"A","b"=>"B","c"=>"C","d"=>"D");	//array_walk -- 对数组中的每个成员应用用户函数	//函数原型:bool array_walk ( array &array, callback funcname [, mixed userdata] )	//第一个参数为 数组	//第二个参数为 callback函数名,	//第三个参数为 可选参数(将传递给所callback的函数)	//==============================================================================	//array_map()将传递callback 函数的 的	//第一个参数是元素的值,如需修改则应加上 &操作符	//第二个参数为键值,如需修改则作如上处理	//第三个参数为用户自己传递给函数的数据(即array_walk()中的第三个参数)		array_walk($arr,'alter',".is.");	?>
Copy after login

输出
a.is.A
b.is.B
c.is.C
d.is.D

----------------------------------------------------------------------------------------

----------------------------------------------------------------------------------------    

   




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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles