0

How could I traverse a structure like below:

    $this->user[$userid] =  array(
                                 "initial" => array(
                                              "amount" =>$amount,
                                              "cards" =>$cards
                                              ),
                                 "userturn" => array(
                                               "userturn1" => array(
                                                              "action"=>$action,
                                                              "amount"=>$amount,
                                                              "date"=>$datetime 
                                                              ),
                                                "userturn2" => array(
                                                              "action"=>$action,
                                                              "amount"=>$amount,
                                                              "date"=>$datetime 
                                                              ),
                                                              .
                                                              .
                                                              .
                                                              .
                                                              n times
                                                     )                                                                

                         );  
4
  • With a nested for loop or a recursive function. Commented Apr 16, 2013 at 12:01
  • First of all format it properly so we don't traverse our neck trying to read it! Commented Apr 16, 2013 at 12:02
  • stackoverflow.com/questions/2930833/… Commented Apr 16, 2013 at 12:03
  • Recommendation: you could include the code you currently have in your question, so that we can help you improve it. Commented Apr 16, 2013 at 12:04

2 Answers 2

1

Assuming you want to get to turns..

foreach($this->user[$userid]['userturn'] as $k=>$turn){
    print_r($turn);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot. what could i do if don't know userid ?
Then you need two cycles foreach($this->user as $userid=>$turns){ foreach($turns[$userid]['userturn'] as $k=>$turn){ print_r($turn); } }
Thanks a lot for help. You made my day. Hats off to you
0

you can use simple recursion:

function recurseLoop($arr){
    foreach($arr as $key=>$value){
         echo('key:' . $key);
         if(gettype($value) == 'array'){
             recurseLoop($value);
         }
         else{
            echo('value:' . $value);
         }

    }
}

recurseLoop($this->user[$userid]);

Comments