从Wordpress $ wpdb构建新的自定义数组
我目前正在使用表的结果并使用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"}
}]
我认为你需要做的是将流程分解成几个步骤(这样你可以改变数据),而不是直接发送你的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 );
我相信这应该是你所需要的基本要点
链接地址: http://www.djcxy.com/p/59413.html