【问题标题】:How to fetch JSON data when the values are in below format?当值采用以下格式时如何获取 JSON 数据?
【发布时间】:2016-04-18 06:10:20
【问题描述】:
{"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_contentsjson_decode 方法从 JSON 中获取数据

【问题讨论】:

  • 您是否尝试过获取任何值?
  • @PaulCrovella 是的,但我正在尝试使用上面指定的其他格式。尝试不同的格式。
  • @MubasharAbbas 我正在尝试从新的 JSON 格式获取值
  • json_decode 将成功解码为 php 对象。接下来,您为第一个数组添加了一些检查,因为它具有标题和数据.. 之后.. 您需要对其余数组进行循环以提取数据。

标签: php arrays json object


【解决方案1】:

这样试试吧。

$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>

【讨论】:

  • 显示为foreach()提供的参数无效
  • 是的。现在它正在显示 JSON 的值。但是如何在文本框或下拉框中显示。
  • $result = $result->result;你确定这是你做的吗?
  • 这是初学者使用的另一个概念
  • 它适用于单值。如何为动态值做呢?如何将其包含在foreach
【解决方案2】:

试试这个

$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;

【讨论】:

    【解决方案3】:

    这里你有一个更动态的方法,不管你有什么标题它都会自动组合,但每一行都需要包含相同的数组长度是非常重要的。

    $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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-04
      • 2020-01-25
      • 1970-01-01
      • 2018-07-03
      相关资源
      最近更新 更多