PHP variable gets last object in database instead of all objects - php

First off, sorry if the title is off...it's the best thing I could think of as to what issue I'm facing.
In my database, I have a list of apps. In PHP, I'm pulling their data from their key, and encoding that data into JSON to be printed out (I'm making an API).
However, only the last app gets printed out in JSON. What I need is a JSON array with ANY apps that have the same key so I can loop through them later, and print out their data.
My code:
$getApp = "SELECT * FROM tundra.apps WHERE app_key = '" . $api_key . "'";
$appData = $dbConnection->query($getApp);
if ($appData->num_rows > 0){ // Check if app_key exists
while($row = $appData->fetch_assoc()) { // While retrieving rows
$jsonApp = json_encode(array( // Encode the row data
"app_name" => $row['app_name'],
"app_theme" => array(
"primary_color" => $row['app_primary_color'],
"primary_color_dark" => $row['app_primary_dark_color'],
"accent_color" => $row['app_accent_color'],
),
"app_navigation" => $row['app_navigation'],
"author_info" => array(
"author_name" => $row['app_author_name'],
"author_bio" => $row['app_author_bio'],
"links" => array(
"website" => $row['app_author_website'],
"googleplus" => $row['app_author_gplus'],
"twitter" => $row['app_author_twitter'],
"dribble" => $row['app_author_dribble'],
"behance" => $row['app_author_behance'],
)
),
"app_status" => $row['app_status']
), JSON_UNESCAPED_SLASHES);
}
// Format and print JSON data
echo "<pre>" . prettyPrint($jsonApp) . "</pre>";
} else { // No key found, encode error
$jsonError = json_encode(
array(
array(
"error" => array(
"code" => "8",
"message" => "Invalid API key specified"
)
)
), JSON_UNESCAPED_SLASHES);
echo "<pre>" . prettyPrint($jsonError) . "</pre>";
}
For the above, I tried echoing the JSON data in the while loop, but that (as expected) printed <pre>s for every row.
Here's the JSON output from the above code:
{
"app_name":"Andrew's Second App",
"app_theme":{
"primary_color":"#FFFFFF",
"primary_color_dark":"#E0E0E0",
"accent_color":"#E91E63"
},
"app_navigation":"0",
"author_info":{
"author_name":"Andrew Quebe",
"author_bio":"I'm a developer of stuff.",
"links":{
"website":"http://www.andrewquebe.com",
"googleplus":"https://plus.google.com/+AndrewQuebe",
"twitter":"https://twitter.com/andrew_quebe",
"dribble":"None",
"behance":"None"
}
},
"app_status":"1"
}
Note: the data is perfectly formatted, but I need the data to be in an array and I'm unsure as to how to do this.

The problem is, you're applying json_encode() function in each iteration of while() loop, plus you're overwriting $jsonApp in each iteration. And that's why you're getting that output.
The solution is, create an empty result array outside of while() loop. In each iteration of while() loop, push that array into the result array. And finally after coming out of the loop, apply json_encode() function on the result array and display it.
So your code should be like this:
// your code
if ($appData->num_rows > 0){ // Check if app_key exists
$resultArr = array();
while($row = $appData->fetch_assoc()) { // While retrieving rows
$resultArr[] = array( // Encode the row data
"app_name" => $row['app_name'],
"app_theme" => array(
"primary_color" => $row['app_primary_color'],
"primary_color_dark" => $row['app_primary_dark_color'],
"accent_color" => $row['app_accent_color'],
),
"app_navigation" => $row['app_navigation'],
"author_info" => array(
"author_name" => $row['app_author_name'],
"author_bio" => $row['app_author_bio'],
"links" => array(
"website" => $row['app_author_website'],
"googleplus" => $row['app_author_gplus'],
"twitter" => $row['app_author_twitter'],
"dribble" => $row['app_author_dribble'],
"behance" => $row['app_author_behance'],
)
),
"app_status" => $row['app_status']
);
}
$jsonApp = json_encode($resultArr, JSON_UNESCAPED_SLASHES);
// Format and print JSON data
echo "<pre>" . prettyPrint($jsonApp) . "</pre>";
} else { // No key found, encode error
$jsonError = json_encode(
array(
array(
"error" => array(
"code" => "8",
"message" => "Invalid API key specified"
)
)
), JSON_UNESCAPED_SLASHES);
echo "<pre>" . prettyPrint($jsonError) . "</pre>";
}

In your while loop, you're constantly re-asigning values to $jsonApp. I would recommend adding the values more like this:
$getApp = "SELECT * FROM tundra.apps WHERE app_key = '" . $api_key . "'";
$appData = $dbConnection->query($getApp);
if ($appData->num_rows > 0){ // Check if app_key exists
for($i=0;$row = $appData->fetch_assoc();i++) { // While retrieving rows
$jsonApp[i] = array( // Encode the row data
"app_name" => $row['app_name'],
"app_theme" => array(
"primary_color" => $row['app_primary_color'],
"primary_color_dark" => $row['app_primary_dark_color'],
"accent_color" => $row['app_accent_color'],
),
"app_navigation" => $row['app_navigation'],
"author_info" => array(
"author_name" => $row['app_author_name'],
"author_bio" => $row['app_author_bio'],
"links" => array(
"website" => $row['app_author_website'],
"googleplus" => $row['app_author_gplus'],
"twitter" => $row['app_author_twitter'],
"dribble" => $row['app_author_dribble'],
"behance" => $row['app_author_behance'],
)
),
"app_status" => $row['app_status']
);
}
$json = json_encode($jsonApp,JSON_UNESCAPED_SLASHES);
// Format and print JSON data
echo "<pre>" . prettyPrint($json) . "</pre>";
} else { // No key found, encode error
$jsonError = json_encode(
array(
array(
"error" => array(
"code" => "8",
"message" => "Invalid API key specified"
)
)
), JSON_UNESCAPED_SLASHES);
echo "<pre>" . prettyPrint($jsonError) . "</pre>";
}
This should show a JSON array, with each element in the array representing an individual app entry.

This is the format of JSON. You can not output different shapes. However, when decoding this JSON output, you can either decode objcet or array.
$object = json_decode($json);
$array = json_decode($json, true);

I believe it's because on line 6 of your example you're assigning the output of json_encode to the $jsonApp variable. It would be easier to use an array like so.
$jsonApp[] = array(
And then use json_encode at the end.
echo "<pre>" . prettyPrint(json_encode($jsonApp)) . "</pre>";

Related

extract json objects from an array in php [duplicate]

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();
}

Using an array value to retrieve from another array

I have created an array, one of the is intended to be a string used by php to display a field from a record retrieved from sqlite3.
My problem is that ... it doesn't.
The array is defined, "1" being the first database field, and "2" is the second database field:
EDIT : I have re-defined the problem as a script so you can see the whole thing:
//If I have an array (simulating a record retrieved from database):
$record = array(
name => 'Joe',
comments => 'Good Bloke',
);
//then I define an array to reference it:
$fields = array(
1 => array(
'db_index' => 'name',
'db_type' => 'TEXT',
'display' => '$record["name"]',
'form_label' => 'Name',
),
2 => array(
'db_index' => 'comments',
'db_type' => 'TEXT',
'display' => '$record["comments"]',
'form_label' => 'Comments',
),
);
//If I use the lines:
print "expected output:\n";
print " Name = " . $record["name"] ."\n";
print " Comments = " . $record["comments"] ."\n";
//I display the results from the $record array correctly.
//However if I try & use the fields array with something like:
Print "Output using Array values\n";
foreach($GLOBALS["fields"] as $field)
{
$label = $field['form_label'];
$it = $field['display'];
$line = "\"$label = \" . $it .\"\n\"";
print $line;
}
Output:
Expected output:
Name = Joe
Comments = Good Bloke
Output using Array values:
Name = $record["name"]
Comments = $record["comments"]
Don't call variable from string. Just concatenate it :
foreach($GLOBALS["fields"] as $field){
$label = $field['form_label'];
$it = $field['display'];
eval("$it = ".$it);
$line = $label." = ".$it."\n";
print $line;
}
Well, how do it looks ?

PHP push array into existing array

I have a php file I am using to create a JSON output. You can see my loop in the code below:
foreach($objQueueData->event as $event){
$output[] = array(
"eventID" => (int)$event->trainingEventID,
"eventTitle" => (string)$event->teTitle,
"eventDescription" => (string)$event->teDesc,
"eventSource" => (string)$event->teSource,
"eventType" => (string)$event->teType,
"eventMedium" => (string)$event->teMedium,
"eventRequestor" => (string)$event->creatorFirst . ' ' . $event->creatorLast,
"eventRequestorNTID" => (string)$event->creatorNTID,
"eventRequestDate" => (string)$event->teCreated,
"eventDirector" => (string)$event->teDirector,
"eventTeammateImpact" => (string)$event->teTeammateImpact,
"eventCustomerImpact" => (string)$event->teCustomerImpact,
"eventComplexity" => (string)$event->teComplexity,
"eventInitiativeID" => (int)$event->intID,
"eventNeededBy" => (string)$event->teNeededBy
);
$impactedRegions = array();
if(isset($event->regionalImpact->option)){
foreach ($event->regionalImpact->option as $region) {
$impactedRegions[] = $region->impact;
}
array_push($output, $impactedRegions);
}
}
// Set the content type to JSON for jquery to understand
header('Content-Type: text/json');
// Print the response to the page
print json_encode($output);
My issue is with the second array impactedRegions. This should be a sub array of output but it is not working as intended.
I am trying to have it be apart of the output array.
Here is what the current JSON output looks like:
[
{
"eventID": 25,
"eventTitle": "Monday",
"eventDescription": "Testing Monday",
"eventSource": "OE",
"eventType": "New Hire",
"eventMedium": "ILT",
"eventRequestor": "Carl",
"eventRequestorNTID": "ch123",
"eventRequestDate": "Nov 17 2014 4:58PM",
"eventDirector": "",
"eventTeammateImpact": "Medium",
"eventCustomerImpact": "High",
"eventComplexity": "Low",
"eventInitiativeID": 1069,
"eventNeededBy": "2014-11-18"
},
[
{
"0": "Americas"
}
],
Can anyone point me in the right direction?
foreach ($event->regionalImpact->option as $region) {
$output['regions'][] = $region->impact;
}
Try this
foreach($objQueueData->event as $key => $event){
$output[$key] = array(
"eventID" => (int)$event->trainingEventID,
"eventTitle" => (string)$event->teTitle,
"eventDescription" => (string)$event->teDesc,
"eventSource" => (string)$event->teSource,
"eventType" => (string)$event->teType,
"eventMedium" => (string)$event->teMedium,
"eventRequestor" => (string)$event->creatorFirst . ' ' . $event->creatorLast,
"eventRequestorNTID" => (string)$event->creatorNTID,
"eventRequestDate" => (string)$event->teCreated,
"eventDirector" => (string)$event->teDirector,
"eventTeammateImpact" => (string)$event->teTeammateImpact,
"eventCustomerImpact" => (string)$event->teCustomerImpact,
"eventComplexity" => (string)$event->teComplexity,
"eventInitiativeID" => (int)$event->intID,
"eventNeededBy" => (string)$event->teNeededBy
);
$impactedRegions = array();
if(isset($event->regionalImpact->option)){
foreach ($event->regionalImpact->option as $region) {
$impactedRegions[] = $region->impact;
}
}
$output[$key]['impactedRegions'] = $impactedRegions;
}
// Set the content type to JSON for jquery to understand
header('Content-Type: text/json');
// Print the response to the page
print json_encode($output);
I think the problem you are having is you are using array_push() with an associative array. I believe array_push is for pushing values to an indexed array.
Trying specifying the key by using $output['impactedRegions'] = $impactedRegions; instead.
$impactedRegions = array();
if(isset($event->regionalImpact->option)){
foreach ($event->regionalImpact->option as $region) {
$impactedRegions[] = $region->impact;
}
$output['impactedRegions'] = json_encode($impactedRegions);
}
Also, json_encode($impactedRegions) will encode the array so it's included as a json object in your original array.

Creating JSON array with information retrieved from database

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']);

How to create an array for JSON using PHP?

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();
}

Categories