从 Wordpress $wpdb->get_results 数组构建新的自定义数组


Build new custom Array from Wordpress $wpdb->get_results array

我目前正在获取表的结果,并使用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。

  1. 构建您自己的阵列
  2. 循环访问 SQL 结果集,同时添加自己的标记
  3. 将输出发送到 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 );

我相信这应该是您需要的基本要点