I am trying to create a JSON array with the information selected from a database but I cannot give the array a name.
while($row = mysql_fetch_array($result))
{
$arr = array('isim' => $row['ename'], 'yer' => $row['eplace'], 'top' => $row['society'], 'tar' => $row['edate'], 'saat' => $row['ehour']);
echo json_encode($arr);
}
I want to see the result;
{"events":[{"isim":"eere","yer":"dddd","top":"asdfsdffgdfgdfg","tar":"2013-10-18","saat":"12:46"}{"isim":"fhjfr","yer":"yhjrhj","top":"ryjryjrj","tar":"2013-10-30","saat":"12:45"}{"isim":"sfsgsg","yer":"sfgssfg","top":"sgsfgsg","tar":"2013-10-31","saat":"12:45"}]}
But I cannot see the
{"events":[
in the beggining and
]}
at the end.
Thank you.
To generate valid JSON, you first need to add everything to a multi-dimensional array and only then when that is complete, encode it:
$arr = array();
while($row = mysql_fetch_array($result))
{
$arr[] = array('isim' => $row['ename'], 'yer' => $row['eplace'], 'top' => $row['society'], 'tar' => $row['edate'], 'saat' => $row['ehour']);
// or perhaps just: $arr[] = $row;
}
echo json_encode($arr);
Also note that the mysql_* functions are deprecated.
To put everything under an events key, you would need something like:
$arr['events'][] = array('isim' => $row['ename'], 'yer' => $row['eplace'], 'top' => $row['society'], 'tar' => $row['edate'], 'saat' => $row['ehour']);
Related
From PHP code I want to create an json array:
[
{"region":"valore","price":"valore2"},
{"region":"valore","price":"valore2"},
{"region":"valore","price":"valore2"}
]
How can I do this?
Easy peasy lemon squeezy: http://www.php.net/manual/en/function.json-encode.php
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
There's a post by andyrusterholz at g-m-a-i-l dot c-o-m on the aforementioned page that can also handle complex nested arrays (if that's your thing).
Use PHP's native json_encode, like this:
<?php
$arr = array(
array(
"region" => "valore",
"price" => "valore2"
),
array(
"region" => "valore",
"price" => "valore2"
),
array(
"region" => "valore",
"price" => "valore2"
)
);
echo json_encode($arr);
?>
Update: To answer your question in the comment. You do it like this:
$named_array = array(
"nome_array" => array(
array(
"foo" => "bar"
),
array(
"foo" => "baz"
)
)
);
echo json_encode($named_array);
Simple: Just create a (nested) PHP array and call json_encode on it. Numeric arrays translate into JSON lists ([]), associative arrays and PHP objects translate into objects ({}). Example:
$a = array(
array('foo' => 'bar'),
array('foo' => 'baz'));
$json = json_encode($a);
Gives you:
[{"foo":"bar"},{"foo":"baz"}]
Best way that you should go every time for creating json in php is to first convert values in ASSOCIATIVE array.
After that just simply encode using json_encode($associativeArray). I think it is the best way to create json in php because whenever we are fetching result form sql query in php most of the time we got values using fetch_assoc function, which also return one associative array.
$associativeArray = array();
$associativeArray ['FirstValue'] = 'FirstValue';
...
etc.
After that.
json_encode($associativeArray);
also for array you can use short annotattion:
$arr = [
[
"region" => "valore",
"price" => "valore2"
],
[
"region" => "valore",
"price" => "valore2"
],
[
"region" => "valore",
"price" => "valore2"
]
];
echo json_encode($arr);
That's how I am able to do with the help of solution given by #tdammers below.
The following line will be placed inside foreach loop.
$array[] = array('power' => trim("Some value"), 'time' => "time here" );
And then encode the array with json encode function
json_encode(array('newvalue'=> $array), 200)
Just typing this single line would give you a json array ,
echo json_encode($array);
Normally you use json_encode to read data from an ios or android app. so make sure you do not echo anything else other than the accurate json array.
I created a crude and simple jsonOBJ class to use for my code. PHP does not include json functions like JavaScript/Node do. You have to iterate differently, but may be helpful.
<?php
// define a JSON Object class
class jsonOBJ {
private $_arr;
private $_arrName;
function __construct($arrName){
$this->_arrName = $arrName;
$this->_arr[$this->_arrName] = array();
}
function toArray(){return $this->_arr;}
function toString(){return json_encode($this->_arr);}
function push($newObjectElement){
$this->_arr[$this->_arrName][] = $newObjectElement; // array[$key]=$val;
}
function add($key,$val){
$this->_arr[$this->_arrName][] = array($key=>$val);
}
}
// create an instance of the object
$jsonObj = new jsonOBJ("locations");
// add items using one of two methods
$jsonObj->push(json_decode("{\"location\":\"TestLoc1\"}",true)); // from a JSON String
$jsonObj->push(json_decode("{\"location\":\"TestLoc2\"}",true));
$jsonObj->add("location","TestLoc3"); // from key:val pairs
echo "<pre>" . print_r($jsonObj->toArray(),1) . "</pre>";
echo "<br />" . $jsonObj->toString();
?>
Will output:
Array
(
[locations] => Array
(
[0] => Array
(
[location] => TestLoc1
)
[1] => Array
(
[location] => TestLoc2
)
[2] => Array
(
[location] => TestLoc3
)
)
)
{"locations":[{"location":"TestLoc1"},{"location":"TestLoc2"},{"location":"TestLoc3"}]}
To iterate, convert to a normal object:
$myObj = $jsonObj->toArray();
Then:
foreach($myObj["locations"] as $locationObj){
echo $locationObj["location"] ."<br />";
}
Outputs:
TestLoc1 TestLoc2 TestLoc3
Access direct:
$location = $myObj["locations"][0]["location"];
$location = $myObj["locations"][1]["location"];
A practical example:
// return a JSON Object (jsonOBJ) from the rows
function ParseRowsAsJSONObject($arrName, $rowRS){
$jsonArr = new jsonOBJ($arrName); // name of the json array
$rows = mysqli_num_rows($rowRS);
if($rows > 0){
while($rows > 0){
$rd = mysqli_fetch_assoc($rowRS);
$jsonArr->push($rd);
$rows--;
}
mysqli_free_result($rowRS);
}
return $jsonArr->toArray();
}
I am passing data base objects to an array.
I need to include another variable to the array. The variable is $latitud_usuario.
Here is the code:
if ($result->num_rows > 0) {
while ($obj = $result->fetch_object()) {
$arr[] = array('nombre_doctor' => $obj->nombre_doctor,'apellido1_doctor' => $obj->apellido1_doctor,'apellido2_doctor' => $obj->apellido2_doctor,'ciudad_doctor' => $obj->ciudad_doctor, 'latitud_doctor' => $latitud_usuario);
}
}
}
echo json_encode($arr);
If I create the array including only fetched objects, the JSON sent is ok, but after including the last array object:
'latitud_doctor' => $latitud_usuario
the JSON is not received as it should.
I guess this last array object expression is wrong.
Any hint is welcome.
Try this
if ($result->num_rows > 0) {
while ($obj = $result->fetch_object()) {
$arr[] = array('nombre_doctor' => $obj->nombre_doctor,'apellido1_doctor' => $obj->apellido1_doctor,'apellido2_doctor' => $obj->apellido2_doctor,'ciudad_doctor' => $obj->ciudad_doctor, 'latitud_doctor' => $latitud_usuario);
$arr['latitud_doctor']=$latitud_usuario;
}
}
}
echo json_encode($arr);
Here's a version that works (using a dummy $obj object):
$obj = (object) array('nombre_doctor'=> 6, 'apellido1_doctor' => 'whatever1', 'apellido2_doctor' => 'whatever2',
'ciudad_doctor' => 'Montreal', 'latitud_usuario' => '35463');
$arr[] = array('nombre_doctor' => $obj->nombre_doctor,'apellido1_doctor' => $obj->apellido1_doctor,
'apellido2_doctor' => $obj->apellido2_doctor,'ciudad_doctor' => $obj->ciudad_doctor,
'latitud_doctor' => $obj->latitud_usuario);
echo json_encode($arr);
I am trying to make a dynamic JSON array in PHP, however when I try to do so it returns "Array". Here is the code I am currently using:
<?php
require '../../scripts/connect.php';
$array = '';
if($result = $db->query("SELECT * FROM art") or die ($db->error)){
if($count = $result->num_rows) {
while($row = $result->fetch_object()){
$array .= array(
'title' => $row->title,
'image' => "http://www.thewebsite.com/img/2.jpg",
'rating' => 7.7,
'releaseYear' => 2003,
'genre' => array(
'0' => $row->category,
'1' => $row->subcategory
)
);
}
}
}
echo json_encode($array);
?>
Can anyone suggest how I might go about fixing this?
And if anyone has suggestions about creating a dynamic JSON array, some help would be much appreciated.
Change your declaration of $array to be an array:
$array = array();
Then in your while loop, when you add the new array to $array, push it like this:
$array[] = array('title'=>$row->title, etc...)
The problem is here: I'm trying to write a code which would make a dynamic PHP array. I have an empty array, to which need to add keys with their values, values being passed by a do-while loop from the MySQL server.
The following php code:
$result=mysqli_query($link,"SELECT products_id,voted,rating FROM table_products $sorting LIMIT 6");
if(mysqli_num_rows($result)>0) {
$a = array();
do {
$row = mysqli_fetch_array($result);
$obj=$row['products_id'];
$rating=$row['rating'];
$voted=$row['voted'];
array_push($a,array('obj'.$obj => array('rating' =>
$rating, 'voted' => $voted)));
} while ($row = mysqli_fetch_array($result)
);}
$json = json_encode($a);
echo $json;
...gives me this json string:
[{"obj1":{"rating":"25","voted":"5"}},{"obj3":{"rating":"36","voted":"10"}},{"obj5":{"rating":"6","voted":"4"}}]
...but I need this:
["obj1":{"rating":"25","voted":"5"},"obj3":{"rating":"36","voted":"10"},"obj5":{"rating":"6","voted":"4"}]
So how can I push this:
'obj'.$obj => array('rating' => $rating, 'voted' => $voted)
whithout putting it in a separate array, like I did in my code? I just don't know a right way to implement this.
Change
array_push($a,array('obj'.$obj => array('rating' => $rating, 'voted' => $voted)));
To
$a['obj'.$obj] = array('rating' => $rating, 'voted' => $voted);
Try this instead of array_push
$a = array_merge($a, array(
'obj'.$obj => array(
'rating' => $rating,
'voted' => $voted
)
));
From PHP code I want to create an json array:
[
{"region":"valore","price":"valore2"},
{"region":"valore","price":"valore2"},
{"region":"valore","price":"valore2"}
]
How can I do this?
Easy peasy lemon squeezy: http://www.php.net/manual/en/function.json-encode.php
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
There's a post by andyrusterholz at g-m-a-i-l dot c-o-m on the aforementioned page that can also handle complex nested arrays (if that's your thing).
Use PHP's native json_encode, like this:
<?php
$arr = array(
array(
"region" => "valore",
"price" => "valore2"
),
array(
"region" => "valore",
"price" => "valore2"
),
array(
"region" => "valore",
"price" => "valore2"
)
);
echo json_encode($arr);
?>
Update: To answer your question in the comment. You do it like this:
$named_array = array(
"nome_array" => array(
array(
"foo" => "bar"
),
array(
"foo" => "baz"
)
)
);
echo json_encode($named_array);
Simple: Just create a (nested) PHP array and call json_encode on it. Numeric arrays translate into JSON lists ([]), associative arrays and PHP objects translate into objects ({}). Example:
$a = array(
array('foo' => 'bar'),
array('foo' => 'baz'));
$json = json_encode($a);
Gives you:
[{"foo":"bar"},{"foo":"baz"}]
Best way that you should go every time for creating json in php is to first convert values in ASSOCIATIVE array.
After that just simply encode using json_encode($associativeArray). I think it is the best way to create json in php because whenever we are fetching result form sql query in php most of the time we got values using fetch_assoc function, which also return one associative array.
$associativeArray = array();
$associativeArray ['FirstValue'] = 'FirstValue';
...
etc.
After that.
json_encode($associativeArray);
also for array you can use short annotattion:
$arr = [
[
"region" => "valore",
"price" => "valore2"
],
[
"region" => "valore",
"price" => "valore2"
],
[
"region" => "valore",
"price" => "valore2"
]
];
echo json_encode($arr);
That's how I am able to do with the help of solution given by #tdammers below.
The following line will be placed inside foreach loop.
$array[] = array('power' => trim("Some value"), 'time' => "time here" );
And then encode the array with json encode function
json_encode(array('newvalue'=> $array), 200)
Just typing this single line would give you a json array ,
echo json_encode($array);
Normally you use json_encode to read data from an ios or android app. so make sure you do not echo anything else other than the accurate json array.
I created a crude and simple jsonOBJ class to use for my code. PHP does not include json functions like JavaScript/Node do. You have to iterate differently, but may be helpful.
<?php
// define a JSON Object class
class jsonOBJ {
private $_arr;
private $_arrName;
function __construct($arrName){
$this->_arrName = $arrName;
$this->_arr[$this->_arrName] = array();
}
function toArray(){return $this->_arr;}
function toString(){return json_encode($this->_arr);}
function push($newObjectElement){
$this->_arr[$this->_arrName][] = $newObjectElement; // array[$key]=$val;
}
function add($key,$val){
$this->_arr[$this->_arrName][] = array($key=>$val);
}
}
// create an instance of the object
$jsonObj = new jsonOBJ("locations");
// add items using one of two methods
$jsonObj->push(json_decode("{\"location\":\"TestLoc1\"}",true)); // from a JSON String
$jsonObj->push(json_decode("{\"location\":\"TestLoc2\"}",true));
$jsonObj->add("location","TestLoc3"); // from key:val pairs
echo "<pre>" . print_r($jsonObj->toArray(),1) . "</pre>";
echo "<br />" . $jsonObj->toString();
?>
Will output:
Array
(
[locations] => Array
(
[0] => Array
(
[location] => TestLoc1
)
[1] => Array
(
[location] => TestLoc2
)
[2] => Array
(
[location] => TestLoc3
)
)
)
{"locations":[{"location":"TestLoc1"},{"location":"TestLoc2"},{"location":"TestLoc3"}]}
To iterate, convert to a normal object:
$myObj = $jsonObj->toArray();
Then:
foreach($myObj["locations"] as $locationObj){
echo $locationObj["location"] ."<br />";
}
Outputs:
TestLoc1 TestLoc2 TestLoc3
Access direct:
$location = $myObj["locations"][0]["location"];
$location = $myObj["locations"][1]["location"];
A practical example:
// return a JSON Object (jsonOBJ) from the rows
function ParseRowsAsJSONObject($arrName, $rowRS){
$jsonArr = new jsonOBJ($arrName); // name of the json array
$rows = mysqli_num_rows($rowRS);
if($rows > 0){
while($rows > 0){
$rd = mysqli_fetch_assoc($rowRS);
$jsonArr->push($rd);
$rows--;
}
mysqli_free_result($rowRS);
}
return $jsonArr->toArray();
}