I have a question. Have a script that renames array keys.
Now I want to do this in a sub level array if needed.
Current situation
The current code I have that works is :
///######## IF THE ORIGINAL KEY HAS BEEN SET
if(isset($this->PreparedData[$key]) === true){
///######## ADD THE DATA TO THE PREPARED DATA VARIABLE
$this->PreparedData[$value] = $this->PreparedData[$key];
///######## UNSET THE ORIGINAL KEY
unset($this->PreparedData[$key]);
}
But I want the code to be able to set the following dynamically:
///######## IF THE ORIGINAL KEY HAS BEEN SET
if(isset($this->PreparedData[$subKey1][$key]) === true){
///######## ADD THE DATA TO THE PREPARED DATA VARIABLE
$this->PreparedData[$subKey1][$value] =$this->PreparedData[$subKey1][$key];
///######## UNSET THE ORIGINAL KEY
unset($this->PreparedData[$subKey1][$key]);
}
Question
But I want to do this dynamically:
So it could be:
$this->PreparedData[$subKey1][$key]
But also:
$this->PreparedData[$subKey1][$subKey2][$key]
But also:
$this->PreparedData[$subKey1][$subKey2][$subKey3][$key]
And this at the hand of an array
Desired situation
So I could set:
MethodName('wheels', array('car', 'mustang'));
That would mean :
$this->PreparedData['car']['mustang']['wheels']
The only question I have.. Is... how to do just this? Because I also want to be able to call:
MethodName('wheels');
Meaning:
$this->PreparedData['wheels']
Thank you!!
The solution is (by splash58):
function MethodName($key, $path = array()) {
global $array;
$p = &$array; // point to array
foreach($path as $step) // walk trough path to needed level
$p = &$p[$step];
return $p[$key]; //take value
}
$array = array( // test array
'wheels'=> 'wheels1',
'car' => array(
'mustang' => array(
'wheels'=> 'wheels2')));
echo MethodName('wheels', array('car', 'mustang')) . "\n"; // wheels2
echo MethodName('wheels'); // wheels1