dongsimang4036 2014-09-12 19:54 采纳率: 100%
浏览 89
已采纳

使用PHP从sql查询中获取特定的JSON数据

I would like to say thank you for reading this question.

And my question is. I have this php code with sql query:

mysql_connect($mysql_server, $mysql_login, $mysql_password);
mysql_select_db($mysql_database);

$req = "SELECT name, elements "
."FROM lwzax_zoo_item "
."WHERE application_id = '2' AND elements LIKE '%".$_REQUEST['term']."%' ";

$query = mysql_query($req);

while($row = mysql_fetch_array($query))
{
    $results[] = array('label' => $row['name'], 'desc' => $row['elements']);
}


$json = json_encode($results);
echo $json;

And output is:

[  
 {  
  "label":"0146T",
  "desc":" {
\t\"cec36dd6-ffde-494d-b25c-8e58bff84e22\": {
\t\t\"0\":        {
\t\t\t\"value\": \"Ccta W\\/Wo Dye\"
\t\t}
\t}
}"
 },
 {  
  "label":"64653",
  "desc":" {
\t\"cec36dd6-ffde-494d-b25c-8e58bff84e22\": {
\t\t\"0\": {
\t\t\t\"value\": \"Chemodenervation Eccrine Glands Oth Area Per Day\"
\t\t}
\t}
}"
 }
]

But I need only label data and value data...so it should look like:

[  
 {  
  "label":"0146T",
  "desc":"Ccta W\\/Wo Dye"
 },
 {  
  "label":"64653",
  "desc":"Chemodenervation Eccrine Glands Oth Area Per Day"
 }
]

Could you please help me? Thank you very much for help

UPDATE: Deleted $b = json_decode($row['desc'], true); as it wasn't used, just a junk from all my attempts to succeed.

  • 写回答

2条回答 默认 最新

  • duansha8115 2014-09-12 20:04
    关注

    You're decoding the JSON and assigning it to $b, but you're not doing anything with that variable. Use:

        $results[] = array('label' => $row['name'],
                           'desc' => $b['cec36dd6-ffde-494d-b25c-8e58bff84e22'][0]['value']);
    

    Also, you need to give a second argument to json_decode, so it will return an associative array rather than an object.

    $b = json_decode($row['elements'], true);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3