简体   繁体   English

将具有相同项目 ID 的多行的 MY SQL 查询结果合并到 json 响应的单行中

[英]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));

Demo演示

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).这将按idtitle对嵌套数组进行分组(我假设相同 id 的 title 是相同的)。

$data would now contain $data现在将包含

[{"id":"1","title":"Title 1","answer":["True","False"]}]

See demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 加入1个表中具有单个ID /行但在另一个表中链接到多个行(相同ID)的SQL查询? - Join SQL query that has single id/row in 1 table, but links to multiple rows(same id) in another table? 我的SQL查询在JSON响应中为3行返回相同的数据类型 - My sql query returns same data type for 3 rows in json response CSV,将多行数据合并为单行和同一列 - CSV, merge multiple rows data into single row and into the same column 将多行SQL查询推送到单个PHP数组项中 - Pushing multiple rows of a SQL query into a single PHP array item SQL多行单行 - SQL multiple rows in single row 在 PHP 中合并具有相同日期列的项目列的行并在单行中显示项目 - Merge rows of item column having the same date column and display items in single row in PHP 如何基于空值和非空值将具有相同字段的两个表行列合并到单个行中? - How to merge two table rows column having same field based on null and not null and result into a single row? 将多个查询合并为 1 个查询 - 在同一行 - Merge Multiple Queries Into 1 Query - On the same Row 如何在 php 中将多个查询结果合并为单个结果 - how merge multiple query result into single result in php php-mysqli-在sql查询中是否搜索ID,如何在此结果上方也获取5行并在其下方获取5行 - php-mysqli - In sql query if search for ID, how to get also 5 row above and 5 rows below this result
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM