这是我的代码,我试图遍历这个json,所以我想做的是当isset($_GET['latest=1']))
它应该从上面的json显示一个对象时,如果latest = 15它应该显示15个对象,我怎么能这样做
<?php
header('Content-Type: application/json');
if(isset($_GET['latest']))
echo
'
{
"contacts": [
{
"id": "c200",
"name": "Ravi Tamada",
"email": "ravi@gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"url": "http://149.202.196.143:8000/live/djemal/djemal/592.ts"
},
{
"id": "c201",
"name": "Johnny Depp",
"email": "johnny_depp@gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"url":"http://149.202.196.143:8000/live/djemal/djemal/592.ts"
},
{
"id": "c202",
"name": "Leonardo Dicaprio",
"email": "leonardo_dicaprio@gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"url":"http://149.202.196.143:8000/live/djemal/djemal/592.ts"
}
]
}
';
答案 0 :(得分:1)
我建议您将数据转换为数组,然后在对数据进行排序后重新编码。
以下可能有一些帮助:
<强> URL:强>
http://localhost/index.php?latest=2
代码 - 第1部分:
这是上面的JSON数据的副本。
$json = ' {
"contacts": [
{
"id": "c200",
"name": "Ravi Tamada",
"email": "ravi@gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"url": "http://149.202.196.143:8000/live/djemal/djemal/592.ts"
},
{
"id": "c201",
"name": "Johnny Depp",
"email": "johnny_depp@gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"url":"http://149.202.196.143:8000/live/djemal/djemal/592.ts"
},
{
"id": "c202",
"name": "Leonardo Dicaprio",
"email": "leonardo_dicaprio@gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"url":"http://149.202.196.143:8000/live/djemal/djemal/592.ts"
}
]
}';
代码 - 第2部分:
$count = (isset($_GET['latest']) && filter_var($_GET['latest'], FILTER_VALIDATE_INT) && $_GET['latest'] >= 1) ? $_GET['latest'] : 1; //To ensure the GET is an INT and set a default value of 1.
$output = json_decode($json, TRUE); //Convert to array
$newArr = []; //Placeholder for new array
for($i=0; $i < $count; $i++) { //Dependent on value (1 being default)
if(isset($output['contacts'][$i])) { //Just incase you get an undefined index issue
$newArr[] = $output['contacts'][$i];
} else {
break; //Break Loop if undefined
}
}
echo json_encode($newArr); //Finally output new array as JSON
输出(值为2):
[{
"id": "c200",
"name": "Ravi Tamada",
"email": "ravi@gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender": "male",
"url": "http:\/\/149.202.196.143:8000\/live\/djemal\/djemal\/592.ts"
}, {
"id": "c201",
"name": "Johnny Depp",
"email": "johnny_depp@gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender": "male",
"url": "http:\/\/149.202.196.143:8000\/live\/djemal\/djemal\/592.ts"
}]
加了: 还添加了一个中断,以防他们要求您的数组中未定义的值。
注意:
速记三元仅适用于PHP 5.3,所以我怀疑你的错误与此有关。 PHP Shorthand ternary operator "?:" Parse error unexpected ":"