PHP index array for JSON - php

Looking for some help.. Don't know the best approach to this issue...
I'm pushing a new reference onto an array but the "true" value is being inserted with quotes, which fails my json format.
while( $row = mysqli_fetch_assoc($res) ) {
if($row['id']=="2"){
$row['children']= 'true';
}
$data[] = $row;
}
echo json_encode( $data);
Outputs
[{"id":"2","name":"john","text":"john","parent_id":"0","children":"true"}]
When i need...
{"id":"2","name":"john","text":"john","parent_id":"0","children":true}]
How would i go about removing the qoutes or inserting it correctly first.??

If you want the 'children' to be boolean then set it to boolean.
while( $row = mysqli_fetch_assoc($res) ) {
if($row['id']=="2"){
$row['children'] = true;
}
$data[] = $row;
}
echo json_encode( $data);

Related

PHP show associative array content into JSON format

i'm new in PHP language. I'm writing a PHP script to get information from my online database(created on my altervista personal webpage) and convert in JSON format.
The problem is about when i get elements from my database i can show them correctly using "echo" command, but when i parse associative array to "json_encode" function i can't see correctly elements.
Here is the code:
$sql = "SELECT * FROM People";
$result = $conn->query($sql);
$json_array = array();
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
foreach($row as $key => $value) {
echo "" . $key . ": " . $value;
echo "<br>";
$json_array[] = array(''=>$key, ''=>$value);
}
} else {
echo "0 results";
}
echo json_encode($json_array);
$conn->close();
?>
The $result->fetch_assoc(); returns an associative array.
As i said before i can see correct information using echo commands.
The problem is when i use this:
$json_array[] = array(''=>$key, ''=>$value);
The output is as follow:
[{"":"Mark"},{"":"ABC"},{"":"25"}]
Basically it's showing me only the second parameter "=>$value", while the first parameter "=>$key" is ignored.
Can you tell me please what should i change in order to see also the first parameter in my output?
Thanks
The correct way would be to do that
$json_array[] = array( $key => $value );
instead of
$json_array[] = array(''=>$key, ''=>$value);
You are essentially adding an EMPTY string as key and the $key as value at first, and then you replace it with the $value as they share the EMPTY string key in the array.
Read more at: http://php.net/manual/en/language.types.array.php#language.types.array.syntax.array-func
First param is ignored because it has the same key as the second (the key is ''), you should write:
$json_array[] = array($key, $value); // Indexed array
Output will be:
[["key1", "value1"],["key2", "value2"],["key3", "value3"]]
OR
$json_array[] = array($key => $value); // Associative array
Output will be:
[{"key1": "value1"},{"key2": "value2"},{"key3": "value3"}]
Try:
sql = "SELECT * FROM People";
$result = $conn->query($sql);
$json_array = array();
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$json_array[] = $row;
}
} else {
echo "0 results";
}
echo json_encode($json_array);
$conn->close();
In your code you are parsing only the first db result

correct way to return a json_object as an array

I have an array populated using an sql statement in the following manner:
$index = 0;
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
$bookname[$index] = ($row['Bookname']);
$subjectname[$index] = ($row['SubjectName']);
$index++;
}
When I go to echo json encode the Arrays I get a blank [] when I know it has been populated which is really weird.
Am I doing anything wrong in my context
echo json_encode($Bookname,$SubjectName);
You can use json_encode as like that:
<?php
$index = 0;
$data = array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
$data[$index]['bookname'] = $row['Bookname'];
$data[$index]['subjectname'] = $row['SubjectName'];
$index++;
}
json_encode($data); // encode your array
?>
Try following:
$index = 0;
$data = array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
$data['Bookname'][$index] = $row['Bookname']
$data['SubjectName'][$index] = $row['SubjectName'];
$index++;
}
echo json_encode($data);
You have passed two parameter while calling json_encode function. You batter combine two array in one. Then call the json_encode function like json_encode($combinedArray)

Json encode an entire mysql result set

I want to get json with php encode function like the following
<?php
require "../classes/database.php";
$database = new database();
header("content-type: application/json");
$result = $database->get_by_name($_POST['q']); //$_POST['searchValue']
echo '{"results":[';
if($result)
{
$i = 1;
while($row = mysql_fetch_array($result))
{
if(count($row) > 1)
{
echo json_encode(array('id'=>$i, 'name' => $row['name']));
echo ",";
}
else
{
echo json_encode(array('id'=>$i, 'name' => $row['name']));
}
$i++;
}
}
else
{
$value = "FALSE";
echo json_encode(array('id'=>1, 'name' => "")); // output the json code
}
echo "]}";
i want the output json to be something like that
{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"}]}
but the output json is look like the following
{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"},]}
As you realize that there is comma at the end, i want to remove it so it can be right json syntax, if i removed the echo ","; when there's more than one result the json will generate like this {"results":[{"id":1,"name":"name1"}{"id":2,"name":"name2"}]} and that syntax is wrong too
Hope that everybody got what i mean here, any ideas would be appreciated
If I were you, I would not json_encode each individual array, but merge the arrays together and then json_encode the merged array at the end. Below is an example using 5.4's short array syntax:
$out = [];
while(...) {
$out[] = [ 'id' => $i, 'name' => $row['name'] ];
}
echo json_encode($out);
Do the json_encoding as the LAST step. Build your data structure purely in PHP, then encode that structure at the end. Doing intermediate encodings means you're basically building your own json string, which is always going to be tricky and most likely "broken".
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] = array('id'=>$i, 'name' => $row['name']);
}
echo json_encode($data);
build it all into an array first, then encode the whole thing in one go:
$outputdata = array();
while($row = mysql_fetch_array($result)) {
$outputdata[] = $row;
}
echo json_encode($outputdata);

json not giving back the proper result from database array

I am getting back two rows from my query, I tested it in phpadmin.
In firebug I can only see the data from one row.
What could be wrong that I don't see?
$data = mysql_fetch_assoc($r);
}
}
header('Content-type: application/json');
$output = array(
"check" => $check,
"users" => $data,
"testnumberoffrows" => $number
);
echo json_encode($output);
in the ajaxfunction
if( data.check ){
var user = data.users;
console.log(user);
thanks, Richard
mysql_fetch_assoc() fetches only one row. You need to loop until it returns FALSE, building up an output array.
Something like this:
while (($row = mysql_fetch_assoc($r)) !== FALSE) {
$data[] = $row;
}
Please try
$got=array();
while ($row = mysql_fetch_array($r)) {
array_push($got, $row);
}
mysql_free_result($r);
header('Content-type: application/json');
$output = array(
"check" => $check,
"users" => $data,
"testnumberoffrows" => $number
);
echo json_encode($output);

format mysql data in array

I am pulling data from my database and trying to encode into JSON data using json_encode. But to make it easier to read in my android app. I was hopping to format it differently then I am currently doing. Please see bottom encode string example. Any help would be great. Thanks in Advance.
$result = $db->query($query);
while($info = mysql_fetch_array($result))
{
$content[] = $info;
}
$count = count($content);
$result=array();
for($i=0;$i<$count;$i++)
{
$result[id][] = $content[$i]['imageID'];
$result[name][] = $content[$i]['Name'];
$result[thumb][] = $content[$i]['Thumb'];
$result[path][] = $content[$i]['Path'];
}
echo json_encode($result);
{"id":["1","2","3"],"name":["Dragon","fly","bug"],"thumb":["thm_polaroid.jpg","thm_default.jpg","thm_enhanced-buzz-9667-1270841394-4.jpg"],"path":["polaroid.jpg","default.jpg","enhanced-buzz-9667-1270841394-4.jpg"]}
But I am trying to format my array like so when it is encoded by json_encode.
[{"id":"1","name":"Dragon","thumb":"thm_polaroid.jpg","path":"polaroid.jpg"},{"id":"2","name":"Fly","thumb":"thm_default.jpg","path":"default.jpg"},{"id":"3","name":"Bug","thumb":"thm_enhanced-buzz-9667-1270841394-4.jpg","path":"enhanced-buzz-9667-1270841394-4.jpg"}]
Well, there is a problem. This is not valid JSON:
{"image":["1","Dragon","thm_polaroid.jpg","polaroid.jpg"],
"image":["2","fly","thm_default.jpg","default.jpg"]}
A JSON object can only have one value per unique key. This means that your latter image key would clobber the value of the former.
If you are content with this, however:
[["1","Dragon","thm_polaroid.jpg","polaroid.jpg"],
["2","fly","thm_default.jpg","default.jpg"]]
Then you can simply use mysql_fetch_row:
$result = $db->query($query);
while($info = mysql_fetch_row($result))
{
$content[] = $info;
}
echo json_encode($content);
Side Note:
Generally, in PHP, it is best to use foreach( $arr as $val ) (or $arr as $key => $val). for loops should be limited to when they are strictly necessary.
You need to add the iterator $i to the setting array
for($i=0;$i<$count;$i++)
{
$result[$i][id] = $content[$i]['imageID'];
$result[$i][name] = $content[$i]['Name'];
$result[$i][thumb] = $content[$i]['Thumb'];
$result[$i][path] = $content[$i]['Path'];
}
<?
$result = $db->query($query);
while($info = mysql_fetch_array($result))
$content[] = $info;
$result=array();
$count = count($content);
for ($x=0;$x<$count;++$x)
{
$result[$x][] = $content[$x]['imageID'];
$result[$x][] = $content[$x]['Name'];
$result[$x][] = $content[$x]['Thumb'];
$result[$x][] = $content[$x]['Path'];
}
echo json_encode($result);
?>

Categories