我目前正在获取表的结果并使用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"
}]
事实上,我并不真正需要其中一些值,还需要格式化一些内容以便于输出以便于地图绘制。例如,国家longform和性别进入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"}
}]
答案 0 :(得分:1)
我认为您需要做的是将流程分解为多个步骤(这样您就可以更改数据),而不是直接将sql数据发送到json。
类似的东西:
$preJSON = array();
// select only columns you need
$sql = "SELECT id, gender, country_srt, lat, long
FROM wp_table"
$count = 0; // this is for $preJSON[] index
foreach( $wpdb->get_results( $sql ) as $key => $row ) {
// each column in your row will now be accessible like this:
// $my_column = $row->column_name;
// now we can do:
$value = $row->id;
$latitude = $row->lat;
$longitude = $row->long;
$gender = $row->gender;
$country = $row->country_srt;
$tooltip = array(
"content" => "HTML and stuff" . $gender . "more HTML and stuff" . $country
);
// now we can build a row of this information in our master array
$preJSON[$count] = array(
"value" => $value,
"latitude" => $latitude,
"longitude" => $longitude,
"tooltip" => $tooltip
);
// increment the index
++$count;
}
// after foreach
// send the whole array to json
$json = json_encode( $preJSON );
我相信这应该是你需要的基本要点