Last active
August 30, 2021 09:32
-
-
Save rennokki/605796a683404ab5a1dd2b12ee4b26b7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
<?php | |
use Illuminate\Support\Collection; | |
/** | |
* This macro will help you turn any nested array into an associative array, | |
* where each element is represented with dot notation. | |
* | |
* For example: | |
* | |
* $arr = [ | |
* 'a' => 1, | |
* 'b' => [ | |
* 'c' => 2, | |
* 'd' => [ | |
* 'e' => 3, | |
* ], | |
* ], | |
* ]; | |
* | |
* will get coverted to: | |
* | |
* $arr = [ | |
* 'a' => 1, | |
* 'b.c' => 2, | |
* 'b.d.e' => 3, | |
* ]; | |
*/ | |
Collection::macro('elementsToDot', function () { | |
/** | |
* @var \Illuminate\Support\Collection $this | |
*/ | |
$recursiveIterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($this->toArray())); | |
$result = []; | |
foreach ($recursiveIterator as $leafValue) { | |
$keys = []; | |
foreach (range(0, $recursiveIterator->getDepth()) as $depth) { | |
$keys[] = $recursiveIterator->getSubIterator($depth)->key(); | |
} | |
$result[implode('.', $keys)] = $leafValue; | |
} | |
return $result; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment