note 112628 deleted from function.array-map by cmb
| From: | cmb@php.net | Date: | Sun, 25 Aug 2019 09:12:09 +0000 |
| Subject: | note 112628 deleted from function.array-map by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212003@lists.php.net to get a copy of this message | ||
Note Submitter: Anonymous
----
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)