note 112628 added to function.array-map

From: Date: Sat, 06 Jul 2013 01:21:47 +0000
Subject: note 112628 added to function.array-map
Groups: php.notes 
Request: Send a blank email to php-notes+get-195473@lists.php.net to get a copy of this message
Simple yet effective associative version of map that accepts arbitrary number of arrays. Instead of elements, result from each() get passed as function arguments. <?php function array_map_assoc(){ if(func_num_args() < 2) throw new \BadFuncionCallException('Missing parameters'); $args = func_get_args(); $callback = $args[0]; if(!is_callable($callback)) throw new \InvalidArgumentException('First parameter musst be callable'); $arrays = array_slice($args, 1); array_walk($arrays, function(&$a){ $a = (array)$a; reset($a); }); $results = array(); $max_length = max(array_map('count', $arrays)); $arrays = array_map(function($pole) use ($max_length){ return array_pad($pole, $max_length, null); }, $arrays); for($i=0; $i < $max_length; $i++){ $elements = array(); foreach($arrays as &$v){ $elements[] = each($v); } unset($v); $out = call_user_func_array($callback, $elements); if($out === null) continue; $val = isset($out[1]) ? $out[1] : null; if(isset($out[0])){ $results[$out[0]] = $val; }else{ $results[] = $val; } } return $results; } //USAGE: $days = array('Sun' => 'Sunday', 'Mon' => 'Monday', 'Tue' => 'Tuesday', 'Wed' => 'Wednesday', 'Thu' => 'Thursday', 'Fri' => 'Friday', 'Sat' => 'Saturday'); $nums = array('First', 'Second', 'Third', 'Fourth', 'Fifth', 'Sixth', 'Seventh'); $result = array_map_assoc(function($a, $b){ return array($b['value'], $a['key']); }, $days, $nums); var_dump($result); //RESULT: array (size=7) 'First' => string 'Sun' (length=3) 'Second' => string 'Mon' (length=3) 'Third' => string 'Tue' (length=3) 'Fourth' => string 'Wed' (length=3) 'Fifth' => string 'Thu' (length=3) 'Sixth' => string 'Fri' (length=3) 'Seventh' => string 'Sat' (length=3) ---- Server IP: 69.147.83.199 Probable Submitter: 195.14.156.34 ---- Manual Page -- http://php.net/manual/en/function.array-map.php Edit -- https://master.php.net/note/edit/112628 Del: integrated -- https://master.php.net/note/delete/112628/integrated Del: useless -- https://master.php.net/note/delete/112628/useless Del: bad code -- https://master.php.net/note/delete/112628/bad+code Del: spam -- https://master.php.net/note/delete/112628/spam Del: non-english -- https://master.php.net/note/delete/112628/non-english Del: in docs -- https://master.php.net/note/delete/112628/in+docs Del: other reasons-- https://master.php.net/note/delete/112628 Reject -- https://master.php.net/note/reject/112628 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#195473) next »