DotNotation.php
<?php
namespace Liaison\Utility;
/**
* Converts between `['i.am.dotted.key' => 'value']` and `['i'=>['am'=>['dotted'=>['key'=>'value']]]]`
* And retrieve value from nested array using dot key
*/
class DotNotation {
/**
* Convert an array from using dotkeys to nested
*
* @return multidemensional / nested array
*/
static public function nestedfromDotted($array){
$nestedArray = [];
foreach ($array as $key=>$value){
$root = self::nestedFromPair($key, $value);
$nestedArray = array_replace_recursive($nestedArray, $root);
}
return $nestedArray;
}
/**
* Convert a single `[dot.key=>value]` pair into a `[dot=>[key=>value]]` nested array
* @return multidemensional/nested array
*/
static public function nestedFromPair($dotKey, $value){
$parts = explode('.',$dotKey);
$root = [];
$flux = &$root;
for ($i=0;$i<($c=count($parts));$i++){
// if ($i==0)continue;
$part = $parts[$i];
$flux[$part] = [];
if ($i==($c-1))$flux[$part] = $value;
else $flux = &$flux[$part];
}
return $root;
}
/**
* Get a value from a nested array, using a dotkey
* @param $dotKey something like `'a.dot.key'`
* @param $nestedArray something like `[a=>[dot=>[key=>'somevalue']]];`
* @return mixed value in the given array
*/
static public function getNestedValue($dotKey, $nestedArray){
$array = $nestedArray;
$parts = explode('.',$dotKey);
$flux = $array;
foreach ($parts as $key){
if (!isset($flux[$key]))return null;
if (!is_array($flux))return null;
$flux = $flux[$key];
}
return $flux;
}
// static public function insertPair(&$array, $key, $value){
// $parts = explode('.',$dotKey);
// // $root = &$array;
// $flux = &$array;
// for ($i=0;$i<($c=count($parts));$i++){
// // if ($i==0)continue;
// $part = $parts[$i];
// $flux[$part] = $flux[$part] ?? [];
// if ($i==($c-1))$flux[$part] = $value;
// else $flux = &$flux[$part];
// }
// }
}