Skip to content

Commit

Permalink
Fixes #854: Added Arr::reverse_flatten.
Browse files Browse the repository at this point in the history
Signed-off-by: Frank de Jonge <info@frenky.net>
  • Loading branch information
frankdejonge committed Mar 18, 2012
1 parent bd93713 commit 052bf11
Showing 1 changed file with 44 additions and 2 deletions.
46 changes: 44 additions & 2 deletions classes/arr.php
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,48 @@ public static function flatten_assoc($array, $glue = ':', $reset = true)
return static::flatten($array, $glue, $reset, false);
}

/**
* Reverse a flattened array in its original form.
*
* @param array $array flattened array
* @param string $glue glue used in flattening
* @return array the unflattened array
*/
public static function reverse_flatten($array, $glue = ':')
{
$return = array();

foreach ($array as $key => $value)
{
if (stripos($key, $glue) !== false)
{
$keys = explode($glue, $key);
$temp =& $return;
while (count($keys) > 1)
{
$key = array_shift($keys);
$key = is_numeric($key) ? (int) $key : $key;
if ( ! isset($temp[$key]) or ! is_array($temp[$key]))
{
$temp[$key] = array();
}
$temp =& $temp[$key];
}

$key = array_shift($keys);
$key = is_numeric($key) ? (int) $key : $key;
$temp[$key] = $value;
}
else
{
$key = is_numeric($key) ? (int) $key : $key;
$return[$key] = $value;
}
}

return $return;
}

/**
* Filters an array on prefixed associative keys.
*
Expand All @@ -316,9 +358,9 @@ public static function filter_prefixed($array, $prefix = 'prefix_', $remove_pref
$return = array();
foreach ($array as $key => $val)
{
if(preg_match('/^'.$prefix.'/', $key))
if (preg_match('/^'.$prefix.'/', $key))
{
if($remove_prefix === true)
if ($remove_prefix === true)
{
$key = preg_replace('/^'.$prefix.'/','',$key);
}
Expand Down

0 comments on commit 052bf11

Please sign in to comment.