Created
May 20, 2017 11:40
-
-
Save adrianalonso/9f92bb2c828f387324f6b622f2105d3f to your computer and use it in GitHub Desktop.
Array Merge with Integer Keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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