[英]Merge MY SQL query result with multiple rows for same item id into single row for json response
I am new to PHP and Wordpress.我是 PHP 和 Wordpress 的新手。 I am trying to build a custom API on Wordpress.
我正在尝试在 Wordpress 上构建自定义 API。 I have a My Sql query that uses INNER JOIN to join 2 tables and returns multiple rows for same item Id.
我有一个 My Sql 查询,它使用 INNER JOIN 连接 2 个表并为同一项目 Id 返回多行。 I am then trying to convert the result set into a JSON response.
然后我尝试将结果集转换为 JSON 响应。
The problem is i am getting a new JSON object for each item Id even if the Ids are same.问题是即使 Id 相同,我也会为每个项目 Id 获取一个新的 JSON 对象。
Please see the My SQL query below:请参阅下面的我的 SQL 查询:
SELECT id, title, answer from wp_tb1 wp1 INNER JOIN wp_tb2 wp2 ON wp1.belongs_id = wp2.id
Php code:代码:
$data=array();
$count=0;
foreach($list as $l){
$data[$count]=array(
"id" =>$l->id,
"title"=>$l->title,
"answer"=> array($l->title),
);
++$count;
}
JSON result looks like: JSON 结果如下所示:
"[{"id":"1","title":"Title 1","answer":"True"},{"id":"1","title":"Title 1","answer":"False"}]"
As you can see, the id value is repeating and so is Title.如您所见,id 值是重复的,Title 也是如此。 I want the response to be something like
我希望响应类似于
"[{"id":"1","title":"Title 1","answer":{"True","False"}}]"
Any help with the query or at the Php code level will be useful.任何有关查询或 PHP 代码级别的帮助都会很有用。
Here an example how create correct json:这是一个如何创建正确 json 的示例:
Method 1:方法一:
try {
// Try Connect to the DB with new MySqli object - Params {hostname, userid, password, dbname}
$mysqli = new mysqli("localhost", "root", "", "mysqli_examples");
$statement = $mysqli->prepare("select id, title, answer from table limit 10");
$statement->execute(); // Execute the statement.
$result = $statement->get_result(); // Binds the last executed statement as a result.
echo json_encode(($result->fetch_assoc())); // Parse to JSON and print.
} catch (mysqli_sql_exception $e) { // Failed to connect? Lets see the exception details..
echo "MySQLi Error Code: " . $e->getCode() . "<br />";
echo "Exception Msg: " . $e->getMessage();
exit(); // exit and close connection.
}
$mysqli->close(); // finally, close the connection
Output:输出:
{
"id": "1",
"title": "Yes pHP",
"answer": "True",
}
Method 2:方法二:
$return_arr = array();
$fetch = $db->query("SELECT * FROM table");
while ($row = $fetch->fetch_array()) {
$row_array['id'] = $row['id'];
$row_array['col1'] = $row['col1'];
$row_array['col2'] = $row['col2'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
Output:输出:
[{"id":"1","col1":"col1_value","col2":"col2_value"},{"id":"2","col1":"col1_value","col2":"col2_value"}]
If your selection
would be always ordered by ID and the main goal is to collect neighboured records with answers then you can use next if statement
:如果您的
selection
总是按 ID 排序,并且主要目标是收集带有答案的相邻记录,那么您可以使用下一个if statement
:
$data = json_decode($data);
$data2=array();
$count=0;
foreach($data as $l){
if ($count % 2 == 0){
$data2[$count]=array(
"id" =>$l->id,
"title"=>$l->title,
);
$data2[$count]['answer'] = [];
$data2[$count]['answer'][] = $l->answer;
} else {
$data2[$count-1]['answer'][] = $l->answer;
}
$count++;
}
print_r(json_encode($data2,JSON_PRETTY_PRINT));
Output is:输出是:
[
{
"id": "1",
"title": "Title 1",
"answer": [
"True",
"False"
]
}
]
If IDs are not ordered then you should to use another code.如果未订购 ID,则应使用其他代码。
Change your loop to this:将您的循环更改为:
$data = [];
foreach ($list as $l) {
$data[$l->id]['id'] = $l->id;
$data[$l->id]['title'] = $l->title;
$data[$l->id]['answer'][] = $l->answer;
}
$data = array_values($data);
This will group the nested array by id
and title
(I'm assuming that title is the same for the same id).这将按
id
和title
对嵌套数组进行分组(我假设相同 id 的 title 是相同的)。
$data
would now contain $data
现在将包含
[{"id":"1","title":"Title 1","answer":["True","False"]}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.