Skip to content

Instantly share code, notes, and snippets.

@hoffigk
Last active January 8, 2016 16:10
Show Gist options
  • Save hoffigk/2693809 to your computer and use it in GitHub Desktop.
Save hoffigk/2693809 to your computer and use it in GitHub Desktop.
Converts array keys to dot notated key path
<?php
class ArrayUtils
{
/**
* Konvertiert einen Array so um, das die Schlüssel als Pfad (punkt notiert)
* umgewandelt werden.
*
* <code>
*
* $source = array(
* 'a' => 1,
* 'b' => array(
* 'c' => 2,
* 'd' => 3
* ),
* 'e' => 4
* );
*
* print_r(ArrayUtils::convertArrayToDotNotatedKeyPathArray($source));
*
* Array
* (
* [a] => 1
* [b.c] => 2
* [b.d] => 3
* [e] => 4
* )
*
* print_r(ArrayUtils::convertArrayToDotNotatedKeyPathArray($source,
* true));
*
* Array
* (
* [0] => a
* [1] => b.c
* [2] => b.d
* [3] => e
* )
*
* </code>
*
* @param array $array
* @param bool $ignoreValues
*
* @return array
*/
public static function convertArrayToDotNotatedKeyPathArray(array $array, $ignoreValues = false)
{
$iterator = new \RecursiveIteratorIterator(
new RecursiveArrayIterator($array), \RecursiveIteratorIterator::SELF_FIRST
);
$lastDepth = 0;
$prefix = array();
$result = array();
foreach ($iterator as $key => $value) {
$difference = $lastDepth - $iterator->getDepth();
if ($difference > 0) {
while ($difference--) {
array_pop($prefix);
}
}
$prefix[] = $key;
$dotPath = implode('.', $prefix);
$lastDepth = $iterator->getDepth();
if (is_array($value)) {
if(is_string(key($value))){
continue;
} else {
if ($ignoreValues) {
$result[] = $dotPath;
} else {
$result[$dotPath] = $value;
}
}
continue;
}
if ($ignoreValues) {
$result[] = $dotPath;
} else {
$result[$dotPath] = $value;
}
array_pop($prefix);
}
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment