从php中的多维关联数组打印值

时间:2019-12-18 12:50:03

标签: php arrays multidimensional-array associative-array

我有一个多维数组,其中包含数据库表中的值,但是值是键值格式,因此我尝试使用foreach循环进行打印但无法获取输出,因此如何使用foreach循环进行此操作 print_r()得到这样的输出之后。

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 . ".";
        }
    }
}

2 个答案:

答案 0 :(得分:0)

您可以尝试:

array_shift($product_info)

然后在其上使用foreach()或简单地遍历:

$product_info['product']

答案 1 :(得分:-1)

这可以解决问题:

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;
    }   

}

您应根据需要对其进行编辑,但这是您可以做到的方式!