Skip to content

Instantly share code, notes, and snippets.

@adrianalonso
Created May 20, 2017 11:40
Show Gist options
  • Save adrianalonso/9f92bb2c828f387324f6b622f2105d3f to your computer and use it in GitHub Desktop.
Save adrianalonso/9f92bb2c828f387324f6b622f2105d3f to your computer and use it in GitHub Desktop.
Array Merge with Integer Keys
class ArrayMergeUtil
{
/**
* @param array $array
*
* @return array
*/
public static function flatArrayAndSumValues(array $array)
{
$result = [];
foreach ($array as $key => $row) {
if (is_array($row)) {
$result[$key] = array_sum($row);
} else {
$result[$key] = $row;
}
}
arsort($result);
return $result;
}
/**
* @param $array
* @return array
*/
function prefixer($array)
{
$out = array();
foreach ($array as $k => $v) {
$out['_' . $k] = $v;
}
return $out;
}
/**
* @param $array
* @return array
*/
function unprefixer($array)
{
$out = array();
foreach ($array as $k => $v) {
$newkey = substr($k, 1);
$out[$newkey] = $v;
}
return $out;
}
/**
* @param $a
* @param $b
* @return array
*/
function array_merge_recursive_improved($a, $b)
{
$a = $this->prefixer($a);
$b = $this->prefixer($b);
$out = $this->unprefixer(array_merge_recursive($a, $b));
return $out;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment