超越PHP PHP动态 | 经典文章 | CLASS | 相关下载 | 常见问题 | FORUM | WIKI | 在线手册
Site search:    
<array_randarray_reverse>
Last updated: Fri, 22 Jun 2007

array_reduce

(PHP 4 >= 4.0.5, PHP 5)

array_reduce --  用回调函数迭代地将数组简化为单一的值

说明

mixed array_reduce ( array input, callback function [, int initial])

array_reduce() 将回调函数 function 迭代地作用到 input 数组中的每一个单元中,从而将数组简化为单一的值。如果指定了可选参数 initial,该参数将被当成是数组中的第一个值来处理,或者如果数组为空的话就作为最终返回值。

例子 1. array_reduce() 例子

<?php
function rsum($v, $w) {
  
$v += $w;
   return
$v;
}

function
rmul($v, $w) {
  
$v *= $w;
   return
$v;
}

$a = array(1, 2, 3, 4, 5);
$x = array();
$b = array_reduce($a, "rsum");
$c = array_reduce($a, "rmul", 10);
$d = array_reduce($x, "rsum", 1);
?>

这将使 $b 的值为 15$c 的值为 1200(= 1*2*3*4*5*10),以及 $d 的值为 1

参见 array_filter()array_map()array_unique()array_count_values()




add a note add a note User Contributed Notes
array_reduce
php dot net at cuntbubble dot com
18-Jan-2002 12:08
There is an error/misleading item in the documentation

[, int initial]

int is not constrained to an integer, it can be any data type (although I've not tested ALL data types)

and $v is the cumulative part, the current value of the reduction.

and I'll take the liberty to add another example, as used in my code

<?php
function reduceToTable($html, $p) {
  $html .= "<TR><TD><a href=\"$p.html\">$p</a></td>\n";
  return $html;
}

$list = Array("page1", "page2", "page3");

$tab = array_reduce($list, "reduceToTable", "<table>\n");
echo $tab . "</table>\n";
?>

hmm, getting stuff on one line sure is tricky, it get's wordwrapped on the char count in html so &gt; counts as 4 chars not one so by the time you've counted "< you've used up 8 chars
If it get's through moderation could someone please make it look ok :)

<array_randarray_reverse>
 Last updated: Fri, 22 Jun 2007
view source | feedback | send page | sitemap | aboutus   
Copyright ® 2002-2003 PHPE.NET. All rights reserved
Last updated:2002-11-22