Skip to content

Commit

Permalink
Multi dimentional array to single dimentional with preserved structur…
Browse files Browse the repository at this point in the history
…e and vice versa
  • Loading branch information
phpmathan committed Jul 2, 2020
1 parent b9b4ca8 commit eca75e9
Showing 1 changed file with 84 additions and 0 deletions.
84 changes: 84 additions & 0 deletions src/stdlib/src/Helper/ArrayHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -1392,4 +1392,88 @@ public static function shuffle($array, $seed = null)

return $array;
}

/**
* Shorten an multidimensional array into a single dimensional array concatenating all keys with separator.
*
* [
* 'country' => [
* 0 => [
* 'name' => 'Bangladesh',
* 'capital' => 'Dhaka'
* ]
* ]
* ]
*
* to [
* 'country.0.name' => 'Bangladesh',
* 'country.0.capital' => 'Dhaka'
* ]
*
* @param array $input
* @param string $separator
* @param string|int $path
*
* @return array
*/
public static function short(array $input, string $separator = '.', $path = null): array
{
$data = [];

if ($path !== null) {
$path .= $separator;
}

foreach ($input as $key => &$value) {
if ((array) $value !== $value) {
$data[$path.$key] = $value;
} else {
$data = array_merge($data, static::short($value, $separator, $path.$key));
}
}

return $data;
}

/**
* Unshorten a single dimensional array into multidimensional array.
*
* [
* 'country.0.name' => 'Bangladesh',
* 'country.0.capital' => 'Dhaka'
* ]
*
* to [
* 'country' => [
* 0 => [
* 'name' => 'Bangladesh',
* 'capital' => 'Dhaka'
* ]
* ]
* ]
*
* @param array $input
* @param string $separator
*
* @return array
*/
public static function unshort(array $input, string $separator = '.'): array
{
$result = [];

foreach ($input as $key => $value) {
if (strpos($key, $separator) !== false) {
$str = explode($separator, $key, 2);
$result[$str[0]][$str[1]] = $value;

if (strpos($str[1], $separator)) {
$result[$str[0]] = static::unshort($result[$str[0]], $separator);
}
} else {
$result[$key] = is_array($value) ? static::unshort($value, $separator) : $value;
}
}

return $result;
}
}

0 comments on commit eca75e9

Please sign in to comment.