1

I am new to PHP and Wordpress. I am trying to build a custom API on Wordpress. I have a My Sql query that uses INNER JOIN to join 2 tables and returns multiple rows for same item Id. I am then trying to convert the result set into a JSON response.

The problem is i am getting a new JSON object for each item Id even if the Ids are same.

Please see the My SQL query below:

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:

"[{"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. 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.

3 Answers3

0

Here an example how create correct 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"}]
Simone Rossaini
  • 8,115
  • 1
  • 13
  • 34
0

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:

$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.

Aksen P
  • 4,564
  • 3
  • 14
  • 27
0

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).

$data would now contain

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

See demo

Paul Spiegel
  • 30,925
  • 5
  • 44
  • 53