This question already has an answer here:
I need to create a json array from only the id
and name
fields below, while outputting the others. How can I best achieve this? I'm trying to get the output like this:
Peter 30 1 Elm Street 91550 {"userId":"1","userName":"Peter"}
James 31 2 Elm Street 91551 {"userId":"2","userName":"James"}
John 32 3 Elm Street 91552 {"userId":"3","userName":"John"}
Andrew 34 4 Elm Street 91553 {"userId":"4","userName":"Andrew"}
I'll use the json array for something else later in a different form. The array keys have to remain the same and cannot be changed.
The output script is pretty simple like this.
$stmt = $conn->prepare("select id, name, age, address, pincode from json");
$stmt->execute();
while( $row = $stmt->fetch() ) {
echo $row['name']." ".$row['age']." ".$row['address']." ".$row['pincode'];
}
I'm currently doing like this, but do you see a better way to do it?
while( $row = $stmt->fetch() ) {
echo $row['name']." ".$row['age']." ".$row['address']." ".$row['pincode'];
$myarray['userId'] = $row['id'];
$myarray['userName'] = $row['name'];
echo json_encode($myarray);
echo '<br>';
}
There are many more fields that'll go into the array. I've used only a few for this example.
</div>