array(9) { [0]=> string(3) "标题1" [1]=> string(3) "">
当前位置:Gxlcms > PHP教程 > 总是搞不懂foreach如何这样遍历这样的数组

总是搞不懂foreach如何这样遍历这样的数组

时间:2021-07-01 10:21:17 帮助过:5人阅读

总是搞不懂foreach怎么这样遍历这样的数组
例如有这样一个数组:
array(4) {
["title"]=>
array(9) {
[0]=>
string(3) "标题1"
[1]=>
string(3) "标题2"
[2]=>
string(3) "标题3"
[3]=>
string(3) "标题4"
}
["id"]=>
array(9) {
[0]=>
string(1) "n1"
[1]=>
string(1) "n2"
[2]=>
string(1) "n3"
[3]=>
string(1) "n4"
}
["pic"]=>
array(9) {
[0]=>
string(4) "https://www.gxlcms.com/1.jpg"
[1]=>
string(4) "https://www.gxlcms.com/2.jpg"
[2]=>
string(4) "https://www.gxlcms.com/3.jpg"
[3]=>
string(4) "https://www.gxlcms.com/4.jpg"
}
["price"]=>
array(9) {
[0]=>
string(5) "85.00"
[1]=>
string(6) "155.00"
[2]=>
string(5) "49.00"
[3]=>
string(5) "75.00"
}
....更多数组

}

我想把里面的数据这样遍历循环出来:



  • 标题1
    85.00





  • 标题2
    155.00





  • 标题3
    49.00





  • 标题4
    75.00




  • 里面应该怎么写的?
    foreach($arr as $key => $value)
    {
    foreach(里面不会写了)
    {
    echo '
  • ';
    echo '';
    echo '';
    echo $title;
    echo ''.$price.'';
    echo '';
    echo '
  • ';
    }
    }

    分享到:


    ------解决方案--------------------
    对于数据
    引用
    $ar = array(
    "title" => array("标题1", "标题2", "标题3", "标题4"),
    "id" => array("n1", "n2", "n3", "n4"),
    "pic" => array("https://www.gxlcms.com/1.jpg", "https://www.gxlcms.com/2.jpg", "https://www.gxlcms.com/3.jpg", "https://www.gxlcms.com/4.jpg"),
    "price" => array("85.00", "155.00", "49.00", "75.00"),
    );
    方法1:
    foreach($ar['id'] as $i=>$r) {
    echo <<< HTML



  • {$ar['title'][$i]}
    {$ar['price'][$i]}


  • HTML;
    }
    方案2
    foreach(array_map(null, $ar['id'], $ar['pic'], $ar['title'], $ar['price']) as $i=>$r) {
    echo <<< HTML



  • $r[2]
    $r[3]


  • HTML;
    }
    均可输出



  • 标题1
    85.00




  • 标题2
    155.00




  • 标题3
    49.00




  • 标题4
    75.00


  • 人气教程排行