使用foreach通过关联数组循环

时间:2016-08-30 19:44:16

标签: php arrays foreach

所以我使用curl从API返回一些JSON,我使用<head> <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *"> <meta name="format-detection" content="telephone=no"> <meta name="msapplication-tap-highlight" content="no"> <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width"> <link rel="stylesheet" type="text/css" href="css/index.css"> <link rel="stylesheet" type="text/css" href="css/bootstrap.css"> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> <title>Hello World</title> <link type="text/css" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.1/css/bootstrap.min.css" /> <style> nav#nav1{margin-top: 24px;} nav#nav1 > a{ background:#B9E1FF; color:#000; padding:10px; text-decoration:none; border-radius:5px; font-family:"Arial Black", Gadget, sans-serif; } nav#nav1 > a:hover{ background: #BBEA00; } nav#nav1 > a:active{ background: #EEFFA8; } </style> <script> var bleep = new Audio(); bleep.src = 'bleep.mp3'; </script> </head> <body> <div class="container"> <nav id="nav1"> <a href="#" onmousedown="bleep.play()">Home</a> <a href="#" onmousedown="bleep.play()">About Us</a> <a href="#" onmousedown="bleep.play()">Services</a> <a href="#" onmousedown="bleep.play()">Contact</a> </nav> </div>

我已设法访问json_decode($result,true);,但我需要遍历整个数组并输出titletitleurllocation

我正在picture打印所有内容:

foreach

什么阻止我如何访问每个元素。

<?php
    foreach ($json as $value) {
        echo "<pre>";
        print_r($json);

        echo $json['data'][2]['title'];
    }
?>

1 个答案:

答案 0 :(得分:-1)

<?php

    foreach ($json as $value) {    

       foreach($value['data'] as $inner){   //looping json['data']
             echo $inner['id'];
             echo $inner['title'];

             foreach($inner['programmes'] as $in_inner){  //looping json['data']['element_number']['programmers']
                 echo $in_inner['id'].':'.$in_inner['short_name'];
              }

       }

    }

?>

通过这种方式,您可以遍历内部数组。