从PHP传递JSON的有效方法 [英] Efficient way to pass JSON from PHP

查看:124
本文介绍了从PHP传递JSON的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我拥有的JSONArray:

Here is a JSONArray I have:

 [{"items_id":"13","total":"1"}, {"items_id":"216","total":"0"},{"items_id":"16","total":"1"}]

有时,每个对象都具有两个以上的属性(属性?).但是我只是在这里展示原则.在Java中,我只需要获取总计"即可.我不需要"items_id".

Sometimes, each object has more than two properties (attributes?). But I am just showing the principle here. In Java, I only need to grab "total". I don't need "items_id".

我认为它显示出来是因为这是我在PHP中的MySQL查询:

I assume it shows up because here is my MySQL query in PHP:

$count_query_result=mysql_query("
SELECT items.items_id, 
COUNT(ratings.item_id) AS total
FROM `items`
LEFT JOIN ratings ON (ratings.item_id = items.items_id)
WHERE items.cat_id = '{$cat_id}'  AND items.spam < 5
GROUP BY items_id ORDER BY TRIM(LEADING 'The ' FROM items.item) ASC;");

这是我的JSON输出(我只显示了上面三个查询之一):

Here is my JSON output (I have only displayed one of three queries above):

print(json_encode(array($output,$output2,$output3)));

我只想要三个用JSON编码的属性(三个输出变量中的每个变量).我想要属性总计",比率"和项目".

I only want three properties encoded in JSON (one in each of the three output variables). I want the properties "total", "rate" ,and "item".

所以我的问题是,我可以摆脱不需要的items_id属性吗?还是我什至需要? (我知道我需要SQL才能使查询正常工作-但是如何在JSONArray中将其删除?)

So my question is, can I get rid of the unneeded items_id property? Or do I even NEED to? (I know I need it in the SQL to make the query work -- but how can I remove it in the JSONArray?)

我在想,如果我有一个包含数百或数千个项目的列表,那么仅输出所需的JSON属性,就可以节省一半的空间(和时间?),这是正确的吗?

I am thinking if I have a list with hundreds or thousands of items, I can save half the space (and time?) by only outputing the JSON property I need -- is this thinking correct?

编辑:根据要求提供更多代码:

Edit: More code as requested:

while($row=mysql_fetch_assoc($count_query_result))
    $output[]=$row;
while($row=mysql_fetch_assoc($average_query_result))
    $output2[]=$row;
while($row=mysql_fetch_assoc($items_query_result))
    $output3[]=$row;

print(json_encode(array($output,$output2,$output3)));
mysql_close();

推荐答案

我认为您的SQL查询中不需要它.如果仅在查询上下文中需要数据库中的数据,则无需SELECT.尝试仅执行以下操作:

I don't think you need it in your SQL query. If you need data from a database just in the context of the query, you don't need to SELECT it. Try doing just the:

SELECT COUNT(*) FROM ...

这篇关于从PHP传递JSON的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆