note 92970 deleted from function.array-reduce by danbrown

From: Date: Mon, 17 Aug 2009 18:26:15 +0000
Subject: note 92970 deleted from function.array-reduce by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-159573@lists.php.net to get a copy of this message
Note Submitter: Anonymous ---- 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.

« previous php.notes (#159573) next »