PHP dynamically get the data from a sub array -


i have question. have script renames array keys.

now want in sub level array if needed.

current situation

the current code have works :

    ///######## if original key has been set     if(isset($this->prepareddata[$key]) === true){         ///######## add data prepared data variable         $this->prepareddata[$value] = $this->prepareddata[$key];         ///######## unset original key         unset($this->prepareddata[$key]);     } 

but want code able set following dynamically:

    ///######## if original key has been set     if(isset($this->prepareddata[$subkey1][$key]) === true){         ///######## add data prepared data variable         $this->prepareddata[$subkey1][$value] =$this->prepareddata[$subkey1][$key];         ///######## unset original key         unset($this->prepareddata[$subkey1][$key]);     } 

question

but want dynamically:

so be:

$this->prepareddata[$subkey1][$key] 

but also:

$this->prepareddata[$subkey1][$subkey2][$key] 

but also:

$this->prepareddata[$subkey1][$subkey2][$subkey3][$key] 

and @ hand of array

desired situation

so set:

methodname('wheels', array('car', 'mustang')); 

that mean :

$this->prepareddata['car']['mustang']['wheels'] 

the question have.. is... how this? because want able call:

methodname('wheels'); 

meaning:

$this->prepareddata['wheels'] 

thank you!!

the solution (by splash58):

function methodname($key, $path = array()) {    global $array;     $p = &$array;                 // point array    foreach($path $step)       // walk trough path 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 

move enviroment

function methodname($key, $path = array()) {    global $array;     $p = &$array;                 // point array    foreach($path $step)       // walk trough path 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 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -