1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55:
<?php
namespace SAREhub\Commons\Misc;
use RecursiveArrayIterator;
use RecursiveIteratorIterator;
class ArrayHelper
{
public static function flatten(array $input, $keySeparator = '.')
{
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($input),
RecursiveIteratorIterator::SELF_FIRST);
$path = [];
$output = [];
foreach ($iterator as $key => $value) {
$path[$iterator->getDepth()] = $key;
if (!is_array($value)) {
$output[implode($keySeparator, array_slice($path, 0, $iterator->getDepth() + 1))] = $value;
}
}
return $output;
}
public static function groupByKey(array $records, $key)
{
return self::groupBy($records, function ($record) use ($key) {
return $record[$key];
});
}
public static function groupBy(array $records, callable $keySelector)
{
$groups = [];
foreach ($records as $record) {
$groups[$keySelector($record)][] = $record;
}
return $groups;
}
}