[php] array_walk — 對陣列中的每個成員應用用戶函數

官方範例:
<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");

function test_alter(&$item1, $key, $prefix)
{
    $item1 = "$prefix: $item1";
}

function test_print($item2, $key)
{
    echo "$key. $item2<br />\n";
}

echo "Before ...:\n";
array_walk($fruits, 'test_print');

array_walk($fruits, 'test_alter', 'fruit');
echo "... and after:\n";

array_walk($fruits, 'test_print');
?>

以上例程會輸出:

Before ...:
d. lemon
a. orange
b. banana
c. apple
... and after:
d. fruit: lemon
a. fruit: orange
b. fruit: banana
c. fruit: apple

其它範例 1
<?php
function myfunction($value,$key)
{
echo "The key $key has the value $value<br />";
}
$a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse");
array_walk($a,"myfunction");
?>

The output of the code above will be:
The key a has the value Cat
The key b has the value Dog
The key c has the value Horse

其它範例 2

With a parameter:
<?php
function myfunction($value,$key,$p)
{
echo "$key $p $value<br />";
}
$a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse");
array_walk($a,"myfunction","has the value");
?>

The output of the code above will be:
a has the value Cat
b has the value Dog
c has the value Horse

其它範例 3

Change an array element's value. (Notice the &$value)
<?php
function myfunction(&$value,$key)
{
$value="Bird;
}
$a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse");
array_walk($a,"myfunction");
print_r($a);
?>

The output of the code above will be:
Array ( [a] => Bird [b] => Bird [c] => Bird )

arrow
arrow
    全站熱搜

    stockwfj3 發表在 痞客邦 留言(0) 人氣()