Skip to content

Instantly share code, notes, and snippets.

@rennokki
Last active August 30, 2021 09:32
Show Gist options
  • Save rennokki/605796a683404ab5a1dd2b12ee4b26b7 to your computer and use it in GitHub Desktop.
Save rennokki/605796a683404ab5a1dd2b12ee4b26b7 to your computer and use it in GitHub Desktop.
<?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