【问题标题】:JSON encode in PHP and MySql [closed]PHP和MySql中的JSON编码[关闭]
【发布时间】:2016-02-04 09:20:54
【问题描述】:

我想要这种类型的 json 使用 php 和 mysql。我尝试了很多,但我得到的 json 是重复数据并且非常复杂。

我需要的 JSON:

{"data":[
    {"Maharashtra":[
        {"Mumbai":[
            {"place_name":"Gateway of India"},
            {"place_name":"Marine Lines"},
            {"place_name":"Juhu"}
            ]},
        {"Pune":[
            {"place_name":"Singhad"},
            ]}
        }],
    {"Goa":[
        {"Panji":[
            {"place_name":"panji"}  
        ]}
    ]}
}]}

PHP 代码:

<?php 
require('database.php'); 

$counter=0; 
$state = "SELECT distinct(s.state_name)
               , ac.city_name 
          FROM all_state s, all_city ac 
          WHERE s.s_id = ac.state_id;"; 

$resultState = $conn->query($state);
$return_arr['data'] = array(); 

while($row = $resultState->fetch_assoc()){
   $getStateName = $row['state_name']; 
   $getCityName = $row['city_name']; 
   $state_array[$getStateName] = array($getCityName);      

   array_push($return_arr['data'], $state_array); 
} 

echo json_encode($return_arr);

【问题讨论】:

  • 您想创建一个 json 或从 json 读取值?请解释清楚
  • 这与 PHP 和 MySQL 有什么关系?我没有看到 PHP 代码和 SQL 语句...
  • 展示你的努力,也展示你的意见,
  • 我想创建 JSON,下面是我的代码 查询($state); $return_arr['data'] = array(); while($row = $resultState -> fetch_assoc() ){ $getStateName = $row['state_name']; $getCityName = $row['city_name']; $state_array[$getStateName] = array($getCityName); array_push($return_arr['data'],$state_array); } 回声 json_encode($return_arr); ?>
  • 问题以不清楚或缺少 MCVE 结束。请参阅How to create a Minimal, Complete, and Verifiable example

标签: php mysql arrays json


【解决方案1】:

您的查询仅返回州和城市,因此数据如下:

{"place_name":"Gateway of India"},
{"place_name":"Marine Lines"},
{"place_name":"Juhu"}

不存在:要将您进入的数据推送到适当的数组,请使用:

while($row = $resultState->fetch_assoc()){
    $stateArray[$row['state']][$row['city']] = array(); // the empty array is there to push your remaining data in to
}
$result = array('data' => $stateArray);
echo json_encode($result);

更新回答评论:

您可以像这样向您的数组添加详细信息(或任何其他方式,有很多,这是最基本的):

$stateArray[$stateYouWant][$cityYouWant]['place_names'] = array('Gateway of India', 'Marine Lines', 'Juhu');

这会给 ytou 类似的东西:

{"Maharashtra":[
    {"Mumbai":[
        {"place_names":[  
            "Gateway of India",
            "Marine Lines",
            "Juhu"]}
        ]},

你想要的变化:

{"Mumbai":[
        {"place_name":"Gateway of India"},
        {"place_name":"Marine Lines"},
        {"place_name":"Juhu"}
        ]},

这是不可能的,因为 json 实际上是关联数组(或 JS 对象)的字符串表示形式,这意味着您不能在同一数组级别上拥有相同的名称键。

【讨论】:

  • 我想在城市数组中打印详细信息.. 怎么做? {"place_name":"印度之门"}, {"place_name":"Marine Lines"}, {"place_name":"巨湖"}
  • 我在 ['place_names'] 上遇到错误 - 错误是非法字符串偏移 'place_names'
  • ofc 你得到了错误,因为你没有创建那个偏移量,你的mysql查询没有返回那个数据
猜你喜欢
  • 2013-03-29
  • 1970-01-01
  • 2020-01-20
  • 2019-04-05
  • 1970-01-01
  • 2011-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多