我的问题是:我如何只显示此代码中的id 2? (代码显示所有id)
这是一个file.php json编码
<?php
header('Content-type: application/json');
$server = "";
$username = "";
$password = "";
$database = "";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$sql = "SELECT * FROM flo";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
相对json结果
([
{
"id":"1",
"Marca":"puma",
},
{
"id":"2",
"Marca":"fila",
}
]);
很多
答案 0 :(得分:0)
为了显示来自JSON的id = 2(或任何其他),必须搜索id,如下所示(将显示&#34; fila&#34;):
<?php
$data = '[ { "id":"1",
"Marca":"puma"
},
{ "id":"2",
"Marca":"fila"
},
{ "id":"3",
"Marca":"nike"
}
]';
$json = json_decode( $data );
foreach ( $json as $record ) // VISIT EACH RECORD.
if ( $record->id == "2" )
echo $record->Marca . "<br/><br/>";
?>
注意数据中的每个字段如何成为JSON中的属性(&#34; id&#34;变为$ record-&gt; id)。