PHP foreach循环遍历包含字符串和数组的数组

时间:2014-10-21 04:15:13

标签: php arrays foreach

我有一个包含字符串和数组的数组。

我试图用foreach获取所有值。为什么不起作用?

<?php

$shirts = array();

$shirts[101] = array(
    "size"  =>  "Large",
    "img" =>  array("images/nike1.jpg","images/nike2.jpg","images/nike3.jpg"),
    "price" => "$30";
);

$shirts[102] = array(
    "size"  =>  "Small",
    "img" =>  array("images/adidas1.jpg","images/adidas2.jpg","images/adidas3.jpg"),
    "price" => "$30";
);

$shirts[103] = array(
    "size"  =>  "Medium",
    "img" =>  array("images/puma1.jpg","images/puma2.jpg","images/puma3.jpg"),
    "price" => "$30";
);

$last = count($shirts) - 1;

foreach ($shirts as $i => $row){
    $isFirst = ($i == 0);
    $isLast = ($i == $last);

    if (is_array($row)){
        $lastChild = count($row) - 1;                       
        foreach ($row as $j =>$rowChild){
            $isFirstChild = ($j == 0);
            $isLastChild = ($j == $lastChild);                          

            echo  $rowChild;    
        }
    }else{
        echo  $row;
    }
}

?>

4 个答案:

答案 0 :(得分:1)

我认为问题出在这一行

foreach ($row as $j =>$rowChild){

由于“img”键内的数组不是键值对,因此该行将失败。你想要的是:

foreach ($row as $rowChild){

答案 1 :(得分:1)

在您的代码中,$row代表:

array(
  "size"  =>  "Large",
  "img" =>  array("images/nike1.jpg","images/nike2.jpg","images/nike3.jpg"),
  "price" => "$30";
)

因此$rowChild代表循环中的"Large"array("images/nike1.jpg","images/nike2.jpg","images/nike3.jpg")"$30"。在第二个循环中,$j不是int索引而是字符串索引("size""img""price")。

当您尝试打印数组时,它会中断。

答案 2 :(得分:0)

如果您正在获取数组到字符串转换错误,我会查看可能触发该错误的行:

  echo  $rowChild; 

如果$ rowChild是一个数组,则回显它不会起作用。例如,如果它是图像文件名数组

答案 3 :(得分:0)

你的foreach循环应该是这样的:

foreach( $shirts as $i=>$row ){

    foreach( $row as $j=>$product ){

        if( is_array( $product ) ){
            foreach( $product as $p ){
                echo $p.'<br>';
            }
        } else {
            echo $product.'<br>';
        }

    }

}