{"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
答案 0 :(得分:2)
试试这样。
$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]
]);
}
}
要在表单元素中显示这些值,例如&#39; dropdown&#39;用这个。
<select name="somename">
<?php foreach($data as $item) { ?>
<option><?= $item['name'] ?></option>
<?php } ?>
</select>
答案 1 :(得分:1)
试试这个
$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;
答案 2 :(得分:0)
这里有一个更动态的方法,无论你自动组合哪个头文件都无关紧要,但每行需要包含相同的数组长度非常重要。
$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);
}