Hi, I need to add a method to my data class to allow other developers (designers really with very limited coding knowledge) to access data in a multidimensional array.
See the following code for what I’m trying to achieve and how far I’ve got…(not very)
I’m not sure which road to take, I was thinking I would look for the last array value and work back looking for a parent key with the preceding value.
Is there a better way?
$data = new Data();
echo $data->get('/location/address/street');
class Data
{
protected $pathSeparator = '/';
protected $data = array(
'name' => array(
'first' => 'John',
'last' => 'Smith',
),
'location' => array(
'address' => array(
'street' => '9454 Wilshire Blvd',
'city' => 'Beverly Hills',
'state' => 'CA',
'country' => 'United States',
'zip' => '90212-2911'
),
'geo' => array(
'latitude' => '0',
'longitude' => '0',
),
),
'email' => 'johnsmith@bmail.com'
);
public function get($path)
{
$path = rtrim($path, $this->pathSeparator);
$array = explode($this->pathSeparator, $path);
}
}
Hmmm, if I understand correctly, you want to return the array value based on the string entered in the get() method?
if so, you could run the function recursively
class Data
{
protected $pathSeparator = '/';
protected $data = array(
'name' => array(
'first' => 'John',
'last' => 'Smith',
),
'location' => array(
'address' => array(
'street' => '9454 Wilshire Blvd',
'city' => 'Beverly Hills',
'state' => 'CA',
'country' => 'United States',
'zip' => '90212-2911'
),
'geo' => array(
'latitude' => '0',
'longitude' => '0',
),
),
'email' => 'johnsmith@bmail.com'
);
public function get($path, array $data = array())
{
$path = rtrim($path, $this->pathSeparator);
//+ Remove firt /
$path = ltrim($path, $this->pathSeparator);
$array = explode($this->pathSeparator, $path);
//+ just declaring a new variable, don't really need this
$newArray = null;
//+ get the first array and reset the pointer
$first = reset($array);
//+ for the recursive function
if( empty($data) ){
$data = $this->data;
}
//+ check if array exists
if( isset($data[$first]) ){
//+ the value to return
$newArray = $data[$first];
//+ check for next array
$next = next($array);
//+ if is array, run the method recursively
if( is_array($newArray) && $next !== false ){
array_shift( $array );
$newPath = implode( $this->pathSeparator, $array);
$value = $this->get($newPath, $newArray);
}else{
$value = $newArray;
}
return $value;
}
return null;
}
}
$data = new Data();
print_r( $data->get('/location/address') );
I’m not entirely sure what you mean by :
allow other developers (designers really with very limited coding knowledge) to access data in a multidimensional array
is that a permissions thing?