function array_update($source, $updates, $keyGen = NULL) {
$out_array = array();
foreach ($source as $key=>$item) {
foreach($updates as $k=>$v){
if (isset($item[$k])) {
$item[$k] = $v;
} else {
throw new Exception("Item has no key $k");
}
}
if (NULL === $keyGen || !is_callable($keyGen)) {
$out_array[$key] = $item;
} else {
$out_array[$keyGen($item)] = $item;
}
}
return $out_array;
}
$out_array = array();
foreach ($source as $key=>$item) {
foreach($updates as $k=>$v){
if (isset($item[$k])) {
$item[$k] = $v;
} else {
throw new Exception("Item has no key $k");
}
}
if (NULL === $keyGen || !is_callable($keyGen)) {
$out_array[$key] = $item;
} else {
$out_array[$keyGen($item)] = $item;
}
}
return $out_array;
}
Although, array_map....
*update*
for some reason, no array_reduce with PHP5.3.3 in Debian, so...
function array_reduce($input, $callback, $initial = NULL) {
$v = $initial;
foreach ($input as $item) {
if (is_callable($callback)) {
$v = $callback($v, $item);
}
}
return $v;
}
$v = $initial;
foreach ($input as $item) {
if (is_callable($callback)) {
$v = $callback($v, $item);
}
}
return $v;
}
No comments:
Post a Comment