0

I have a problem creating a recursive function to convert a list to an object :

   location :
       12 : 
         label : 'city 1'
         children:
              13 :
                label:'city2'
                children :
                   14 : 
                     label : 'city3'
                   15 : 
                     label : 'city4'
                     children :
                            16 : 
                                  .....
                                 .....

              122 :
                label : 'city 100'

    ........

So I hope to create a recursive function to return an object with all my list above with something like that :

 public static function getLocation($config , $id )
 {
    $id= current($config['id'])
    $label =   $config['id']['label']
    $children = $config['id']['label']['children']
    ....
    if(!empty($children) ){

    }else{

       foreach( ){
           getLocation($config , $id );
       }
    }
    return $obj;

 }
hakre
  • 193,403
  • 52
  • 435
  • 836
Nll
  • 819
  • 5
  • 19
  • 41

1 Answers1

0

If you want to transform an array into a std class, you can use this script :

function arrayToObject($d) {
    if (is_array($d)) {
        /*
        * Return array converted to object
        * Using __FUNCTION__ (Magic constant)
        * for recursive call
        */
        return (object) array_map(__FUNCTION__, $d);
    }
    else {
        // Return object
        return $d;
    }
}
artragis
  • 3,677
  • 1
  • 18
  • 30