note 92970 added to function.array-reduce

From: Date: Mon, 17 Aug 2009 15:35:18 +0000
Subject: note 92970 added to function.array-reduce
Groups: php.notes 
Request: Send a blank email to php-notes+get-159564@lists.php.net to get a copy of this message
To Hrobky: Actually you can reduce array of arrays. Reduce callback must convert accumulator from integer to array on the first pass. This script will count number of word uses in text by using map/reduce: <?php function lcount($string) { return array($string => 1); } function rcount($w1, $w2) { if (!is_array($w1)) { $w1 = array(); } foreach ($w2 as $word => $count) { $w1[$word] += $count; } return $w1; } $text = 'Mary had a little lamb Its fleece was white as snow When Mary was in trouble The lamb was first to go'; $result = array_reduce(array_map('lcount', explode(' ', $text)), 'rcount'); arsort($result); var_dump($result); ?> Array_map changes each word to array(word => 1). Reduce function will summarize this array's values. ---- Server IP: 64.71.164.2 Probable Submitter: 91.207.100.2 ---- Manual Page -- http://www.php.net/manual/en/function.array-reduce.php Edit -- https://master.php.net/note/edit/92970 Del: integrated -- https://master.php.net/note/delete/92970/integrated Del: useless -- https://master.php.net/note/delete/92970/useless Del: bad code -- https://master.php.net/note/delete/92970/bad+code Del: spam -- https://master.php.net/note/delete/92970/spam Del: non-english -- https://master.php.net/note/delete/92970/non-english Del: in docs -- https://master.php.net/note/delete/92970/in+docs Del: other reasons-- https://master.php.net/note/delete/92970 Reject -- https://master.php.net/note/reject/92970 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#159564) next »