简体   繁体   中英

print values from multidimensional associative array in php

I have multidimensional array which contain values from database table but values are key value format so I tried to print using foreach loop but unable to get output ,so how to do this using foreach loop after print_r() getting output like this.

echo '<pre>';
print_r($product_info);


Array
(
    [product] => Array
        (
            [0] => Array
                (
                    [data1] => "value1"  
                )
            [1] => Array
                (
                    [data2] => "value2"  
                )
        )
    [type] => 6
)

foreach ($product_info as $key => $val) {
    if (is_array($val)) {
         foreach ($val as $c => $d) {
            echo "" . $c . " is " . $d . ".";
        }
    }
}

You can try to:

array_shift($product_info)

And then use foreach() on it or simply iterate over:

$product_info['product']

This will do the trick:

foreach ($product_info as $key => $val) {

    //look for specific key. And do action if needed.
    if($key=='product'){

        $all = 0;
        $all = COUNT($val); //Count lines

        //loop lines
        for ($x = 0; $x <= $all; $x++) {

            //check if line exist
            if(isset($val[$x])){

                //loop through lines and echo data
                foreach ($val[$x] as $c => $d) {

                    echo $c.' '.$d.'<br>';

                }
            }
        }       


    }

    if($key=='type'){       
        echo 'This is type: '.$val;
    }   

}

You should edit it for your needs but this is how you could do it!

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