简体   繁体   中英

PHP foreach of multidimensional array

I have an array and it has two arrays inside of it...I am able to access what I want for the first row by doing this...

print_r( $_SESSION['shopcart']['cart']['qty']);

How would I write that in a foreach?

Thanks, J

foreach($_SESSION['shopcart']['cart']['qty'] as $value) {
    echo $value;
}

you would do something like this:

to dump the array: $_SESSION['shopcart']['cart']

foreach($_SESSION['shopcart']['cart'] as $key=>$value){
    echo $key." => ".$value."<br/>";
}

If you want to iterate through multiple dimensions, you can nest foreach as follows:

foreach($_SESSION['shopcart'] as $cart) {
    foreach ($cart as $qty) {
        // do something
    }
}

Though I'd need a little more information about the array structure and what you really want to do in order to provide usable code, this is probably in the right ballpark.

I would recommend you you do do like this:

foreach($_SESSION['shopcart'] as $key=>$value){
    if(is_array( $value ) ){
       foreach($value => k1 => $v1){

        //do something here if array 

         echo $k1." => ".$v1."<br/>";
       }
    }else{
         //do something here if not array 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM