php array_walk示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php array_walk示例相关的知识,希望对你有一定的参考价值。

<span style="color: #808080; font-style: italic;">// the test array </span>
<span style="color: #0000ff;">$array</span> = <a href="http://www.php.net/array"><span style="color: #000066;">array</span></a><span style="color: #66cc66;">&#40;</span>
    <span style="color: #ff0000;">'php'</span>, <span style="color: #ff0000;">'arrays'</span>, <span style="color: #ff0000;">'are'</span>, <span style="color: #ff0000;">'cool'</span>    
<span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">// some variable for testing:</span>
<span style="color: #0000ff;">$some_var</span> = <span style="color: #ff0000;">'NEW'</span>;
&nbsp;
&nbsp;
<span style="color: #808080; font-style: italic;">// the function that get's called for each entry</span>
<span style="color: #000000; font-weight: bold;">function</span> format_array_values<span style="color: #66cc66;">&#40;</span>&amp;<span style="color: #0000ff;">$item</span>, <span style="color: #0000ff;">$key</span>, <span style="color: #0000ff;">$some_var</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #0000ff;">$item</span> = <span style="color: #0000ff;">$some_var</span> . <span style="color: #ff0000;">&quot;: $item (KEY: $key)&lt;br/&gt;&quot;</span>;
<span style="color: #66cc66;">&#125;</span>
&nbsp;
&nbsp;
<span style="color: #808080; font-style: italic;">// &quot;walk&quot; trough each array item and call the function:</span>
<span style="color: #808080; font-style: italic;">// &quot;format_array_values&quot;</span>
<a href="http://www.php.net/array_walk"><span style="color: #000066;">array_walk</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$array</span>, <span style="color: #ff0000;">'format_array_values'</span>, <span style="color: #0000ff;">$some_var</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">// print the result:</span>
<a href="http://www.php.net/print_r"><span style="color: #000066;">print_r</span></a><span style="color: #66cc66;">&#40;</span><span style="color: #0000ff;">$array</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
<span style="color: #808080; font-style: italic;">/*
The output will be:
&nbsp;
Array
(
    [0] =&gt; NEW: php (KEY: 0)&lt;br/&gt;
    [1] =&gt; NEW: arrays (KEY: 1)&lt;br/&gt;
    [2] =&gt; NEW: are (KEY: 2)&lt;br/&gt;
    [3] =&gt; NEW: cool (KEY: 3)&lt;br/&gt;
)
*/</span>

以上是关于php array_walk示例的主要内容,如果未能解决你的问题,请参考以下文章

PHP array_walk() 函数详解

PHP array_walk() 函数

PHP array_walk() 函数,对数组中应用自定义函数

php [php:array_walk]带闭包的破坏性阵列扫描。 #PHP

PHP 合并两个二维数组 array_map 和 array_walk 的区别

php中array_walk() 和 array_map()两个函数区别