Skip to content

Instantly share code, notes, and snippets.

@MattiJarvinen-BA
Created March 16, 2012 08:15
Show Gist options
  • Save MattiJarvinen-BA/2049085 to your computer and use it in GitHub Desktop.
Save MattiJarvinen-BA/2049085 to your computer and use it in GitHub Desktop.
Simple unoptimized functions to translate PHP array notation string for example html input name and its value to array and vice versa.
<?php
/**
* Attach value $value to array path:
* attachValueToArrayPath('valueHere','foo[bar]')
* results array('foo'=>array('bar'=>'valuehere'));
*
* @param mixed $value
* @param string $path
* @return array
*/
function attachValueToArrayPath($value,$path)
{
if( strpos($path, '[') === false )
{
return array($path=>$value);
}
$pathElements = array();
// theres gotta be easier way
while( strpos($path, '[') !== false)
{
$arrayPos = strpos($path, '[');
// Get the next key in the path starting from previous [
$arrayKey = substr($path, 0,$arrayPos);
$pathElements[] = trim($arrayKey);
// Set the next search point in the path
$path = substr($path, $arrayPos+1);
$path = substr_replace ($path , "", strpos($path, ']'),1);
}
$pathElements[] = $path;
$pathElements = array_reverse($pathElements);
$return = array();
$pointer = &$return;
do
{
// get key to set
$key = array_pop($pathElements);
// if it is the last key
if(count($pathElements) == 0)
{
// set correct value
$pointer = array($key => $value);
}else
{
// prepare for next key
$pointer[$key]=array();
// move pointer
$pointer = &$pointer[$key];
}
}while(count($pathElements)>0);
return $return;
}
/**
* Determines value for array path eg. foo[bar] from $value array
* reverse of attachValueToArrayPath.
*
* @see attachValueToArrayPath
* @param mixed $value
* @param string $path
* @return mixed
*/
protected function extractValueFromPath($value,$path)
{
// if found straight
if(isset($value[$path]))
{
return $value[$path];
}
// More parts
while( $arrayPos = strpos($path, '[') )
{
// Get the next key in the path starting from previous [
$arrayKey = trim(substr($path, 0, $arrayPos), ']');
// Set potentially final value or the next search point in the array
// handles recursion here
if(isset($value[$arrayKey]))
{
$value = $value[$arrayKey];
}
// Set the next search point in the path
$path = trim(substr($path, $arrayPos + 1), ']');
}
if(isset($value[$path]))
{
$value = $value[$path];
}else
{
$value = null;
}
return $value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment