我在这里做错了什么?
当我只有一个结果回来时,这段代码完美无缺
$someObject = json_decode($data);
$id=$someObject->clips[0]->id;
但是当我想做一个循环因为我可能得到10个结果这个代码不起作用,我相信我错过了一些非常简单的事情
$someObject = json_decode($data);
//var_dump($someObject);
foreach($someObject as $json){
echo $json->clips[0]->id;
}
编辑: 这个解决方案适用于任何想要看的人
foreach ($someObject->clips as $clip){
echo $clip->id. "<br>";
}
不确定另一个人如何回答我所遇到的for循环问题。
答案 0 :(得分:2)
您需要将此索引[0]
更改为动态索引。
foreach($someObject as $k => $json){
echo $json->clips[$k]->id; // Insert $k here
}
答案 1 :(得分:1)
更改此
foreach($someObject as $json){
echo $json->clips[0]->id;
}
到
$i=0;
foreach($someObject as $json){
echo $json->clips[$i]->id;
$i++;
}
或miken32在评论中说明
foreach ($someObject->clips as $clip){
echo $clip->id;
}
答案 2 :(得分:1)
阅读此参考文献:control-structures.foreach.php
如果你想让所有项目迭代你可以使用foreach ,在php数组中
成像你有这个样本json:
<?php
$data = array("username" => "test"); // data u want to post
$data_string = json_encode($data);
$api_key = "your_api_key";
$password = "xxxxxx";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://xxxxxxxxxxxxxxxxxxxxxxx");
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $api_key.':'.$password);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'Content-Type: application/json')
);
if(curl_exec($ch) === false)
{
echo 'Curl error: ' . curl_error($ch);
}
$errors = curl_error($ch);
$result = curl_exec($ch);
$returnCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo $returnCode;
var_dump($errors);
print_r(json_decode($result, true));
如果您想获取剪辑和标签列表,可以使用以下代码:
{
"clips": [{
"id": 1,
"name": "test",
"tags": [
"tag1",
"tag2",
"tag3"
]
},
{
"id": 2,
"name": "test2",
"tags": [
"tag4",
"tag5",
"tag6"
]
}
]
}