【发布时间】:2015-03-09 03:41:44
【问题描述】:
我目前正在获取表格的结果并使用 wp_send_json 将其用作 JSON 响应。数据按预期编码,但是我想通过更改键、格式和顺序来稍微调整输出。我不确定如何重建数组并编码为 json,所以我正在寻找一些帮助。
$stuff= $wpdb->get_results( $wpdb->prepare("SELECT * FROM wp_table"), ARRAY_A);
wp_send_json($stuff);
到目前为止,我通过 print_r 获得的结果如下所示。
Array(
[0] => Array(
[id] => 1[gender] => Male[email] => test@loas . com[lat] => 38[long] => - 97[country_srt] => USA[country_long] => UnitedStates
) [1] => Array(
[id] => 2[gender] => Female[email] => femal@test . com[lat] => 38[long] => - 97[country_srt] => USA[country_long] => UnitedStates
)
)
编码后我得到:
[{
"id": "1",
"gender": "Male",
"email": "test@loas.com",
"lat": "45",
"long": "-76",
"country_srt": "USA",
"country_long": "United States"
}, {
"id": "2",
"gender": "Female",
"email": "femal@test.com",
"lat": "98",
"long": "-34",
"country_srt": "USA",
"country_long": "United States"
}]
问题是,我真的不需要其中的一些值,并且还需要格式化一些内容以输出以便于绘制地图。例如,国家长格式和性别进入一个 html 格式的字符串。我要做的是转换这个数组以产生:
[ idhere: {
"value": "1",
"latitude": "45",
"longitude": "-76",
"tooltip": {"content":"HTML Showing gender variable and country variable"}
}, idhere: {
"value": "2",
"latitude": "98",
"longitude": "-34",
"tooltip": {"content":"HTML Showing gender variable and country variable"}
}]
【问题讨论】:
-
然后只需更改您的查询,只需包含您想要的列
-
改变我的查询方式?我不确定我是否遵循这个简单的答案。
-
@Ghost 将查询限制在所需的特定列并不能解决将您自己的标记添加到最终 json 的方面
-
@DrewT 当然还有更多内容,这就是为什么它是一个评论 :),而
$count是多余的,只需像往常一样推送它$array[] = array here -
@Ghost 运行增量
$count索引在技术上比在 php 中推送到数组在性能上更快。请参阅此线程中的基准:stackoverflow.com/questions/559844/… 这也是一种首选方法,因为它有助于调试循环,因为您可以在任何断点处输出它的值。