gpt4 book ai didi

php - SQL/WordPress/AJAX : Format JSON With Loop

转载 作者:行者123 更新时间:2023-11-29 02:18:24 26 4
gpt4 key购买 nike

问题

我正在尝试查询我的数据库(wp_usermeta 表)并将其导出为 JSON 格式以供自动完成插件处理。我需要这样格式化数据:

{"suggestion":"copmany1", "umeta_id":"1"},{"suggestion":"company2", "umeta_id":"2"}, etc.

到目前为止

我当前的代码输出这样的信息:

{"suggestions":["concept9 test","Company"],"data":["58","77"]}

这是我的代码:

$query = $_GET["query"];



// escape values passed to db to avoid sql-injection
$query = $wpdb->get_results( "SELECT DISTINCT umeta_id, meta_value FROM wp_usermeta WHERE meta_key='company' AND meta_value LIKE '".$query."%' order by umeta_id" );

$suggestions = array();

foreach($query as $row) {
$suggestions[] = $row->meta_value;
$data[] = $row->umeta_id;

$response1 = array(
'suggestions' => $suggestions,
'data' => $data,
);
}


$response = json_encode( $response1 );
echo $response;
exit();

谢谢!

最佳答案

像这样尝试:

$query = $_GET["query"];
// escape values passed to db to avoid sql-injection
$query = $wpdb->get_results( "SELECT DISTINCT umeta_id, meta_value FROM wp_usermeta WHERE meta_key='company' AND meta_value LIKE '".$query."%' order by umeta_id" );
$suggestions = array();
foreach($query as $row) {
array_push($suggestions, array(
'suggestion' => $row->meta_value,
'umeta_id' => $row->umeta_id
)
);
}
echo json_encode( $suggestions );
exit();

如果您需要进一步的解释,请在此处评论

关于php - SQL/WordPress/AJAX : Format JSON With Loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35724559/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com