1

I have two MySQL output which I need to encode in a single JSON output.

Output 1:

$sql = "select * from t1 ORDER BY id DESC LIMIT 25";
$result = $conn->query($sql);

    while($row = $result->fetch_assoc()) {
    $output[] = array_map("nl2br", $row);
    }

Output 2:

$sql2 = "select * from t2 ORDER BY id DESC LIMIT 25";
$result2 = $conn->query($sql2);

    while($row2 = $result2->fetch_assoc()) {
    $output2[] = array_map("nl2br", $row2);
    }

This is what I am doing to get them in single JSON_encode:

echo json_encode($output.$output2);

still not getting both the outputs. I came to know of another solutions i.e. to merge both the queries but I am not able to do that as well. I referred this question also but no luck :(

4
  • 2
    json_encode(array($output, $output2)); Commented Jul 14, 2015 at 8:50
  • @PaulBain Thanks for your help But this is giving the output as [[{"id":"1"}],[{"id":"2"}]] and I need the output as [{"id":"1"},{"id":"2"}] Commented Jul 14, 2015 at 8:56
  • So just append your stuff to the first array. Instead of $output2[] = array_map("nl2br", $row2); do $output[] = array_map("nl2br", $row2); And finally do json_encode($output) Commented Jul 14, 2015 at 8:59
  • @Marius This didn't helped :( Commented Jul 14, 2015 at 9:07

1 Answer 1

3
  1. How about using UNION in your query? Please check it out here: https://dev.mysql.com/doc/refman/5.0/en/union.html

  2. What about

    $fullOutput = array_merge($output1, $output2); echo json_encode($fullOutput);

Sign up to request clarification or add additional context in comments.

1 Comment

$fullOutput = array_merge($output1, $output2); did it!! Thanks a lot!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.