{"cities":[{"city":{"id":1,"name":"Bangalore","status":"Active"}},
{"city":{"id":2,"name":"Mysore","status":"Active"}},... ]}
以上是 JSON 格式,这是我从 JSON 中获取的方式,如下所示,
$city=$data['cities'];
$citycount=count($city);
for($i=0;$i<$citycount;$i++)
{
echo $data['cities'][$i]['city']['id'];
}
现在如何在格式如下时获取 JSON 值
{"result":[["id","name","status"],[1,"Bangalore","Active"],[2,"Mysore","Active"],... ]}
我正在使用核心 PHP 通过方法 file_get_contents
和 json_decode
从 JSON 获取数据
试试这个。
$result = json_decode($newjson);
$result = $result->result;
$data = [];
$headers= $result[0]; // get the first row.
foreach($result as $key => $row) {
// ignore the headers row.
if($key != 0) {
array_push($data, [
$headers[0] => $row[0],
$headers[1] => $row[1],
$headers[2] => $row[2]
]);
}
}
要在"下拉列表"等表单元素中显示这些值,请使用此选项。
<select name="somename">
<?php foreach($data as $item) { ?>
<option><?= $item['name'] ?></option>
<?php } ?>
</select>
试试这个
$json = '{"result":[["id","name","status"],[1,"Bangalore","Active"],[2,"Mysore","Active"]]} ';
$result = json_decode($json,true);
$dataArray = [];
foreach($result['result'] as $key => $value) {
if($key != 0) {
array_push($dataArray, [
$result['result'][0][0] => $value[0],
$result['result'][0][1] => $value[1],
$result['result'][0][2] => $value[2]
]);
}
}
print_r($dataArray);
exit;
在这里,您有一个更动态的方法,无论您拥有什么标题,它都会自动组合,但非常重要的一点是,每行都需要包含相同的数组长度。
$data = '{"result":[["id","name","status"],[1,"Bangalore","Active"],[2,"Mysore","Active"]]}';
$_data = json_decode($data);
if(!empty($_data)){
$i = 0; //I know that the first row is the header
foreach($_data->result as $row){
if($i++ == 0){
$header = $row;
continue;
}
$newData[] = array_combine($header, $row);
}
echo '<pre>';
print_r($newData);
}