Wednesday, 29 August 2018

PHP echoing the multidimensional array as JSON

I am trying to display all the users in my database in JSON form in an array. This is what I have - but it is not in the form that I want it in

{
  "username": [
    "bobgreen",
    "jacksmitd",
    "samson",
  ]
  "forename": [
    "Bob",
    "Jack",
    "Sam",
  ],
  "surname": [
    "O'Conor",
    "Smitd",
    "Son",
  ]
}

This is my code that gives this output...
if(mysqli_num_rows($outcome)){
    while($row = mysqli_fetch_assoc($outcome)){
        $finalOutcome["username"][] = $row["username"];
        $finalOutcome["forename"][] = $row["forename"];
        $finalOutcome["surname"][] = $row["surname"];
    }
    echo json_encode($finalOutcome);
}

I want to store all of the relevant details within braces so like:
{
    "username":"bobgreen"
    "forename":"Bob"
    "surname":"O'Conor"
}
{
    "username":"jacksmitd"
    "forename":"Jack"
    "surname":"Smitd"
}
{
    "username":"samson"
    "forename":"Sam"
    "surname":"Son"
}

Also how do I extract all the relevant data from each brace and store in a list in Java? Because I am trying to store all the details on a per users basis and I wasn't sure how to do it with my first JSON array

Regarding main question:
You have to use this syntax:
while( $row = mysqli_fetch_assoc( $outcome ) )
{
    $finalOutcome[] = array
    (
        "username" => $row["username"],
        "forename" => $row["forename"],
        "surname"  => $row["surname"]
    );
}
echo json_encode( $finalOutcome );

Substantially, in your original query you increment $finalOutcome sub-arrays instead of $finalOutcome

0 comments:

Post a Comment