PHP/Data Structure/array walk — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 10:02, 26 мая 2010
Apply a user function to every member of an array.
<source lang="html4strict">
<? $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
\n";
} array_walk ($fruits, "test_print"); reset ($fruits); array_walk ($fruits, "test_alter", "fruit"); reset ($fruits); array_walk ($fruits, "test_print"); ?>
</source>
Applying Functions to Array Elements Using array_walk()
<source lang="html4strict">
<?php
function array_display($array, $pre=FALSE) { $tag = $pre ? "pre" : "p"; printf("<%s>%s</%s>\n", $tag, var_export($array, TRUE), $tag); } function modify(&$element) { $element *= 1.5; } $array = array(10, -3.5, 2, 7); array_display($array, TRUE); array_walk($array, "modify"); array_display($array, TRUE);
?>
</source>
array_walk() function applies a function to several or all elements in an array.
<source lang="html4strict">
Its syntax is: int array_walk(array array, string func_name, [mixed data])
<? //Using array_walk() to delete duplicates in an array:
function delete_dupes($element) { static $last=""; if ($element == $last) unset($element); else $last=$element; } $emails = array("b@b.ru", "c@w.ru", "b@b.ru"); sort($emails); print_r($emails); echo "
"; reset($emails); print_r($emails); echo "
"; array_walk($emails,"delete_dupes"); print_r($emails); echo "
";
?>
</source>