循环多维数组与重复项

时间:2017-07-27 09:21:15

标签: php arrays multidimensional-array

$pplinfo  = array(

        array("name" => "alan",
              "sex" => "male",
              "favourite" => "white","black","pink" 
        ),
        array(  "name" => "eric",
                "sex" => "male",
                "favourite" => "red","grey","navy","white","purple","chocolate" 
        ),
);

如何获得foreach循环函数的结果如下,

阿兰是一个像白人一样的男性

阿兰是一个像黑人一样的男性

阿兰是一个喜欢粉红色的男性

埃里克是一个喜欢红色的男性

埃里克男性喜欢灰色

埃里克是一个喜欢海军的男性

埃里克是一个喜欢白人的男性

埃里克是一个像紫色的男性

埃里克是一个喜欢巧克力的男性

1 个答案:

答案 0 :(得分:0)

希望favourite也是数组。使用它可以达到如下结果:

$pplinfo  = array(

  array(
          "name" => "alan",
          "sex" => "male",
          "favourite" => array("white","black","pink")

  ),
  array(
          "name" => "eric",
          "sex" => "male",
          "favourite" => array("red","grey","navy","white","purple","chocolate")

  ),
);

foreach ($pplinfo as $key => $value) {
  $favourites = $value['favourite'];
  foreach ($favourites as $favourite) {    
    echo $value['name']." is a ".$value['sex']." like ".$favourite;
    echo "<br>";
  }
}