我有一个像下面这样的对象,数组相互嵌套。我使用 foreach 循环来遍历数组的第一层和第二层。
array (
'totalHits' => 500,
'total' => 845,
'hits' =>
array (
0 => array (
'url' => 'www.someurl.com',
'id' => '11',
),
1 => array (
'url' => 'www.differenturl.com',
'id' => '22',
),
);
我试图从嵌套在“hits”中的所有数组中获取键和值,但我只得到第一个,hits[0]。我错过了什么?
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$keywords = $_POST['pixa_keyword'];
$api_key = "my_hidden_api_key";
$url = "https://pixabay.com/api/?key=".$api_key."&safesearch=true&q=".$keywords;
$json = file_get_contents($url);
}
?>
<body>
<form action="#" method="post">
<input name="pixa_keyword" id="cms_pixaSearchKeywords2" type="text" value="">
<input name="submit_pixa_search" id="cms_pixaSearchBtn2" type="submit" value="search">
</form>
<div id="cms_displayPixaResults"></div>
<?php
$pixa_feedback=[];
if($_SERVER['REQUEST_METHOD']=="POST"){
$pixa_feedback = json_decode($json);
}
foreach($pixa_feedback as $inner){
// check type
if(is_array($inner)){
// iterate through nested array
$i = 0;
foreach ($inner[$i] as $key => $value){
echo $key . ": " . $value . " <br>";
$i++;
}
}
}
?>
繁星coding
ibeautiful
哆啦的时光机