PHP/Data Structure/array map — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 10:02, 26 мая 2010
Applying Functions to Array Elements Using array_map()
<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 calc_sqrt($num) { $i = $num < 0 ? "i" : ""; return sqrt( abs($num) ) . $i; } $values = array(3, 8, -3, 0, 14, -4); $roots = array_map("calc_sqrt", $values);print "
Values:
";array_display($values, TRUE);print "
Square roots:
";array_display($roots, TRUE);
?>
</source>
Using array_map() and array_walk() together
<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 get_pay($emp, $hr, $rt) { return sprintf("%s worked %.2f hours, and grossed $%.2f", $emp, $hr, $rt * $hr); } function display_pd_emp(&$el) {printf("
%s.
\n", $el);} $employees = array("A", "B", "C", "D", "N"); $hours = array(35.2, 37.4, 41.3, 28.8, 38.5); $rates = array(12.5, 12.5, 13.75, 9.85, 11.6); $paid_emps = array_map("get_pay", $employees, $hours, $rates); array_walk($paid_emps, "display_pd_emp"); array_display($paid_emps, TRUE);
?>
</source>
Using the array_map() Function
<source lang="html4strict">
<?php
function my_callback($var) { echo "Value: $varecho "
"; return strtoupper($var); } $myarray = array("hello", "this", "is", "a", "callback!"); $newarray = array_map("my_callback", $myarray);
"; print_r($newarray); echo "";
?>
</source>