简体   繁体   English

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

[英]Get specific JSON data from sql query using PHP

I would like to say thank you for reading this question. 我要说谢谢您阅读这个问题。

And my question is. 我的问题是。 I have this php code with sql query: 我有这个PHP代码与SQL查询:

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":" {\n\t\"cec36dd6-ffde-494d-b25c-8e58bff84e22\": {\n\t\t\"0\":        {\n\t\t\t\"value\": \"Ccta W\\/Wo Dye\"\n\t\t}\n\t}\n}"
 },
 {  
  "label":"64653",
  "desc":" {\n\t\"cec36dd6-ffde-494d-b25c-8e58bff84e22\": {\n\t\t\"0\": {\n\t\t\t\"value\": \"Chemodenervation Eccrine Glands Oth Area Per Day\"\n\t\t}\n\t}\n}"
 }
]

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); 更新:删除$ b = json_decode($ row ['desc'],true); as it wasn't used, just a junk from all my attempts to succeed. 没用过,只是我所有成功的尝试中的一个垃圾。

You're decoding the JSON and assigning it to $b , but you're not doing anything with that variable. 您正在解码JSON并将其分配给$b ,但是您没有对该变量执行任何操作。 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. 另外,您需要给json_decode提供第二个参数,这样它将返回一个关联数组而不是对象。

$b = json_decode($row['elements'], true);

OK, well, first things first, initialize your array OUTSIDE your loop. 好吧,首先,首先,在循环之外初始化数组。

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

Then you should probably do this: 然后,您可能应该这样做:

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

The at the end 最后

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

See if that helps. 看看是否有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM