Read data from JSON in PHP [duplicate] - javascript

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 9 months ago.
This post was edited and submitted for review last month and failed to reopen the post:
Original close reason(s) were not resolved
I tried to parse a JSON file using PHP. But I am stuck now.
This is the content of my JSON file:
{
"John": {
"status":"Wait"
},
"Jennifer": {
"status":"Active"
},
"James": {
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
}
And this is what I have tried so far:
<?php
$string = file_get_contents("/home/michael/test.json");
$json_a = json_decode($string, true);
echo $json_a['John'][status];
echo $json_a['Jennifer'][status];
But because I don't know the names (like 'John', 'Jennifer') and all available keys and values (like 'age', 'count') beforehand, I think I need to create some foreach loop.
I would appreciate an example for this.

To iterate over a multidimensional array, you can use RecursiveArrayIterator
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n";
} else {
echo "$key => $val\n";
}
}
Output:
John:
status => Wait
Jennifer:
status => Active
James:
status => Active
age => 56
count => 10
progress => 0.0029857
bad => 0
run on codepad

I can't believe so many people are posting answers without reading the JSON properly.
If you foreach iterate $json_a alone, you have an object of objects. Even if you pass in true as the second parameter, you have a two-dimensional array. If you're looping through the first dimension you can't just echo the second dimension like that. So this is wrong:
foreach ($json_a as $k => $v) {
echo $k, ' : ', $v;
}
To echo the statuses of each person, try this:
<?php
$string = file_get_contents("/home/michael/test.json");
if ($string === false) {
// deal with error...
}
$json_a = json_decode($string, true);
if ($json_a === null) {
// deal with error...
}
foreach ($json_a as $person_name => $person_a) {
echo $person_a['status'];
}
?>

The most elegant solution:
$shipments = json_decode(file_get_contents("shipments.js"), true);
print_r($shipments);
Remember that the json-file has to be encoded in UTF-8 without BOM. If the file has BOM, then json_decode will return NULL.
Alternatively:
$shipments = json_encode(json_decode(file_get_contents("shipments.js"), true));
echo $shipments;

Try
<?php
$string = file_get_contents("/home/michael/test.json");
$json_a = json_decode($string,true);
foreach ($json_a as $key => $value){
echo $key . ':' . $value;
}
?>

It's completely beyond me that no one pointed out that your begining "tags" are wrong. You're creating an object with {}, while you could create an array with [].
[ // <-- Note that I changed this
{
"name" : "john", // And moved the name here.
"status":"Wait"
},
{
"name" : "Jennifer",
"status":"Active"
},
{
"name" : "James",
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
] // <-- And this.
With this change, the json will be parsed as an array instead of an object. And with that array, you can do whatever you want, like loops etc.

Try This
$json_data = '{
"John": {
"status":"Wait"
},
"Jennifer": {
"status":"Active"
},
"James": {
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
}';
$decode_data = json_decode($json_data);
foreach($decode_data as $key=>$value){
print_r($value);
}

Try:
$string = file_get_contents("/home/michael/test.json");
$json = json_decode($string, true);
foreach ($json as $key => $value) {
if (!is_array($value)) {
echo $key . '=>' . $value . '<br />';
} else {
foreach ($value as $key => $val) {
echo $key . '=>' . $val . '<br />';
}
}
}

More standard answer:
$jsondata = file_get_contents(PATH_TO_JSON_FILE."/jsonfile.json");
$array = json_decode($jsondata,true);
foreach($array as $k=>$val):
echo '<b>Name: '.$k.'</b></br>';
$keys = array_keys($val);
foreach($keys as $key):
echo ' '.ucfirst($key).' = '.$val[$key].'</br>';
endforeach;
endforeach;
And the output is:
Name: John
Status = Wait
Name: Jennifer
Status = Active
Name: James
Status = Active
Age = 56
Count = 10
Progress = 0.0029857
Bad = 0

Loop through the JSON with a foreach loop as key-value pairs. Do type-checking to determine if more looping needs to be done.
foreach($json_a as $key => $value) {
echo $key;
if (gettype($value) == "object") {
foreach ($value as $key => $value) {
# and so on
}
}
}

<?php
$json = '{
"response": {
"data": [{"identifier": "Be Soft Drinker, Inc.", "entityName": "BusinessPartner"}],
"status": 0,
"totalRows": 83,
"startRow": 0,
"endRow": 82
}
}';
$json = json_decode($json, true);
//echo '<pre>'; print_r($json); exit;
echo $json['response']['data'][0]['identifier'];
$json['response']['data'][0]['entityName']
echo $json['response']['status'];
echo $json['response']['totalRows'];
echo $json['response']['startRow'];
echo $json['response']['endRow'];
?>

Try it:
foreach ($json_a as $key => $value)
{
echo $key, ' : ';
foreach($value as $v)
{
echo $v." ";
}
}

When you decode a json string, you will get an object. not an array. So the best way to see the structure you are getting, is to make a var_dump of the decode. (this var_dump can help you understand the structure, mainly in complex cases).
<?php
$json = file_get_contents('/home/michael/test.json');
$json_a = json_decode($json);
var_dump($json_a); // just to see the structure. It will help you for future cases
echo "\n";
foreach($json_a as $row){
echo $row->status;
echo "\n";
}
?>

$json_a = json_decode($string, TRUE);
$json_o = json_decode($string);
foreach($json_a as $person => $value)
{
foreach($value as $key => $personal)
{
echo $person. " with ".$key . " is ".$personal;
echo "<br>";
}
}

The quickest way to echo all json values is using loop in loop, the first loop is going to get all the objects and the second one the values...
foreach($data as $object) {
foreach($object as $value) {
echo $value;
}
}

You have to give like this:
echo $json_a['John']['status'];
echo "<>"
echo $json_a['Jennifer']['status'];
br inside <>
Which gives the result :
wait
active

I am using below code for converting json to array in PHP,
If JSON is valid then json_decode() works well, and will return an array,
But in case of malformed JSON It will return NULL,
<?php
function jsonDecode1($json){
$arr = json_decode($json, true);
return $arr;
}
// In case of malformed JSON, it will return NULL
var_dump( jsonDecode1($json) );
?>
If in case of malformed JSON, you are expecting only array, then you can use this function,
<?php
function jsonDecode2($json){
$arr = (array) json_decode($json, true);
return $arr;
}
// In case of malformed JSON, it will return an empty array()
var_dump( jsonDecode2($json) );
?>
If in case of malformed JSON, you want to stop code execution, then you can use this function,
<?php
function jsonDecode3($json){
$arr = (array) json_decode($json, true);
if(empty(json_last_error())){
return $arr;
}
else{
throw new ErrorException( json_last_error_msg() );
}
}
// In case of malformed JSON, Fatal error will be generated
var_dump( jsonDecode3($json) );
?>

Related

json_encode works for integers not for strings

I am trying to pass arrays from php to js and the json_encode function works on $MID (integer array) but fails to do anything on $name (array of strings).
Can anybody help me understand why it won't work?
$sql = "SELECT DISTINCT [materialID],[name],[categoryName],[materialResponsePerson]
FROM [SAP_Replication].[dbo].[IntranetProductResponsePerson]";
$params = array();
$stmt = sqlsrv_query( $conn, $sql, $params);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
$MID = array();
$name = array();
$cName = array();
$resPerson = array();
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
array_push($MID,$row["materialID"]);
array_push($name,$row["name"]);
array_push($cName,$row["categoryName"]);
array_push($resPerson,$row["materialResponsePerson"]);
}
echo json_encode($MID); //works and returns values
echo json_encode($name); //returns bool(false)
sqlsrv_close($conn);
Only echo one thing back to the Javascript! It is expecting to get one reply from your PHP code and not 4.
so I would do
echo json_encode([ 'MID' => $MID,
'name' => $name,
'cName' => $cName,
'resPerson' => $resPerson
]);
Then change your js code to read data from the right object
I have made a mistake when commenting the code. When I var_dump the $name variable it returns bool(false). Later I found out that meant that json_encode doesn't support string which have 'đ','ž','...' in them so I need to convert the array to utf-8.
Thanks everyone for the help.

How to Convert json code to php object? [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 9 months ago.
This post was edited and submitted for review last month and failed to reopen the post:
Original close reason(s) were not resolved
I tried to parse a JSON file using PHP. But I am stuck now.
This is the content of my JSON file:
{
"John": {
"status":"Wait"
},
"Jennifer": {
"status":"Active"
},
"James": {
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
}
And this is what I have tried so far:
<?php
$string = file_get_contents("/home/michael/test.json");
$json_a = json_decode($string, true);
echo $json_a['John'][status];
echo $json_a['Jennifer'][status];
But because I don't know the names (like 'John', 'Jennifer') and all available keys and values (like 'age', 'count') beforehand, I think I need to create some foreach loop.
I would appreciate an example for this.
To iterate over a multidimensional array, you can use RecursiveArrayIterator
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n";
} else {
echo "$key => $val\n";
}
}
Output:
John:
status => Wait
Jennifer:
status => Active
James:
status => Active
age => 56
count => 10
progress => 0.0029857
bad => 0
run on codepad
I can't believe so many people are posting answers without reading the JSON properly.
If you foreach iterate $json_a alone, you have an object of objects. Even if you pass in true as the second parameter, you have a two-dimensional array. If you're looping through the first dimension you can't just echo the second dimension like that. So this is wrong:
foreach ($json_a as $k => $v) {
echo $k, ' : ', $v;
}
To echo the statuses of each person, try this:
<?php
$string = file_get_contents("/home/michael/test.json");
if ($string === false) {
// deal with error...
}
$json_a = json_decode($string, true);
if ($json_a === null) {
// deal with error...
}
foreach ($json_a as $person_name => $person_a) {
echo $person_a['status'];
}
?>
The most elegant solution:
$shipments = json_decode(file_get_contents("shipments.js"), true);
print_r($shipments);
Remember that the json-file has to be encoded in UTF-8 without BOM. If the file has BOM, then json_decode will return NULL.
Alternatively:
$shipments = json_encode(json_decode(file_get_contents("shipments.js"), true));
echo $shipments;
Try
<?php
$string = file_get_contents("/home/michael/test.json");
$json_a = json_decode($string,true);
foreach ($json_a as $key => $value){
echo $key . ':' . $value;
}
?>
It's completely beyond me that no one pointed out that your begining "tags" are wrong. You're creating an object with {}, while you could create an array with [].
[ // <-- Note that I changed this
{
"name" : "john", // And moved the name here.
"status":"Wait"
},
{
"name" : "Jennifer",
"status":"Active"
},
{
"name" : "James",
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
] // <-- And this.
With this change, the json will be parsed as an array instead of an object. And with that array, you can do whatever you want, like loops etc.
Try This
$json_data = '{
"John": {
"status":"Wait"
},
"Jennifer": {
"status":"Active"
},
"James": {
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
}';
$decode_data = json_decode($json_data);
foreach($decode_data as $key=>$value){
print_r($value);
}
Try:
$string = file_get_contents("/home/michael/test.json");
$json = json_decode($string, true);
foreach ($json as $key => $value) {
if (!is_array($value)) {
echo $key . '=>' . $value . '<br />';
} else {
foreach ($value as $key => $val) {
echo $key . '=>' . $val . '<br />';
}
}
}
More standard answer:
$jsondata = file_get_contents(PATH_TO_JSON_FILE."/jsonfile.json");
$array = json_decode($jsondata,true);
foreach($array as $k=>$val):
echo '<b>Name: '.$k.'</b></br>';
$keys = array_keys($val);
foreach($keys as $key):
echo ' '.ucfirst($key).' = '.$val[$key].'</br>';
endforeach;
endforeach;
And the output is:
Name: John
Status = Wait
Name: Jennifer
Status = Active
Name: James
Status = Active
Age = 56
Count = 10
Progress = 0.0029857
Bad = 0
Loop through the JSON with a foreach loop as key-value pairs. Do type-checking to determine if more looping needs to be done.
foreach($json_a as $key => $value) {
echo $key;
if (gettype($value) == "object") {
foreach ($value as $key => $value) {
# and so on
}
}
}
<?php
$json = '{
"response": {
"data": [{"identifier": "Be Soft Drinker, Inc.", "entityName": "BusinessPartner"}],
"status": 0,
"totalRows": 83,
"startRow": 0,
"endRow": 82
}
}';
$json = json_decode($json, true);
//echo '<pre>'; print_r($json); exit;
echo $json['response']['data'][0]['identifier'];
$json['response']['data'][0]['entityName']
echo $json['response']['status'];
echo $json['response']['totalRows'];
echo $json['response']['startRow'];
echo $json['response']['endRow'];
?>
Try it:
foreach ($json_a as $key => $value)
{
echo $key, ' : ';
foreach($value as $v)
{
echo $v." ";
}
}
When you decode a json string, you will get an object. not an array. So the best way to see the structure you are getting, is to make a var_dump of the decode. (this var_dump can help you understand the structure, mainly in complex cases).
<?php
$json = file_get_contents('/home/michael/test.json');
$json_a = json_decode($json);
var_dump($json_a); // just to see the structure. It will help you for future cases
echo "\n";
foreach($json_a as $row){
echo $row->status;
echo "\n";
}
?>
$json_a = json_decode($string, TRUE);
$json_o = json_decode($string);
foreach($json_a as $person => $value)
{
foreach($value as $key => $personal)
{
echo $person. " with ".$key . " is ".$personal;
echo "<br>";
}
}
The quickest way to echo all json values is using loop in loop, the first loop is going to get all the objects and the second one the values...
foreach($data as $object) {
foreach($object as $value) {
echo $value;
}
}
You have to give like this:
echo $json_a['John']['status'];
echo "<>"
echo $json_a['Jennifer']['status'];
br inside <>
Which gives the result :
wait
active
I am using below code for converting json to array in PHP,
If JSON is valid then json_decode() works well, and will return an array,
But in case of malformed JSON It will return NULL,
<?php
function jsonDecode1($json){
$arr = json_decode($json, true);
return $arr;
}
// In case of malformed JSON, it will return NULL
var_dump( jsonDecode1($json) );
?>
If in case of malformed JSON, you are expecting only array, then you can use this function,
<?php
function jsonDecode2($json){
$arr = (array) json_decode($json, true);
return $arr;
}
// In case of malformed JSON, it will return an empty array()
var_dump( jsonDecode2($json) );
?>
If in case of malformed JSON, you want to stop code execution, then you can use this function,
<?php
function jsonDecode3($json){
$arr = (array) json_decode($json, true);
if(empty(json_last_error())){
return $arr;
}
else{
throw new ErrorException( json_last_error_msg() );
}
}
// In case of malformed JSON, Fatal error will be generated
var_dump( jsonDecode3($json) );
?>

using returned result in JSON multidimensional array [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 9 months ago.
This post was edited and submitted for review last month and failed to reopen the post:
Original close reason(s) were not resolved
I tried to parse a JSON file using PHP. But I am stuck now.
This is the content of my JSON file:
{
"John": {
"status":"Wait"
},
"Jennifer": {
"status":"Active"
},
"James": {
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
}
And this is what I have tried so far:
<?php
$string = file_get_contents("/home/michael/test.json");
$json_a = json_decode($string, true);
echo $json_a['John'][status];
echo $json_a['Jennifer'][status];
But because I don't know the names (like 'John', 'Jennifer') and all available keys and values (like 'age', 'count') beforehand, I think I need to create some foreach loop.
I would appreciate an example for this.
To iterate over a multidimensional array, you can use RecursiveArrayIterator
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($json, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n";
} else {
echo "$key => $val\n";
}
}
Output:
John:
status => Wait
Jennifer:
status => Active
James:
status => Active
age => 56
count => 10
progress => 0.0029857
bad => 0
run on codepad
I can't believe so many people are posting answers without reading the JSON properly.
If you foreach iterate $json_a alone, you have an object of objects. Even if you pass in true as the second parameter, you have a two-dimensional array. If you're looping through the first dimension you can't just echo the second dimension like that. So this is wrong:
foreach ($json_a as $k => $v) {
echo $k, ' : ', $v;
}
To echo the statuses of each person, try this:
<?php
$string = file_get_contents("/home/michael/test.json");
if ($string === false) {
// deal with error...
}
$json_a = json_decode($string, true);
if ($json_a === null) {
// deal with error...
}
foreach ($json_a as $person_name => $person_a) {
echo $person_a['status'];
}
?>
The most elegant solution:
$shipments = json_decode(file_get_contents("shipments.js"), true);
print_r($shipments);
Remember that the json-file has to be encoded in UTF-8 without BOM. If the file has BOM, then json_decode will return NULL.
Alternatively:
$shipments = json_encode(json_decode(file_get_contents("shipments.js"), true));
echo $shipments;
Try
<?php
$string = file_get_contents("/home/michael/test.json");
$json_a = json_decode($string,true);
foreach ($json_a as $key => $value){
echo $key . ':' . $value;
}
?>
It's completely beyond me that no one pointed out that your begining "tags" are wrong. You're creating an object with {}, while you could create an array with [].
[ // <-- Note that I changed this
{
"name" : "john", // And moved the name here.
"status":"Wait"
},
{
"name" : "Jennifer",
"status":"Active"
},
{
"name" : "James",
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
] // <-- And this.
With this change, the json will be parsed as an array instead of an object. And with that array, you can do whatever you want, like loops etc.
Try This
$json_data = '{
"John": {
"status":"Wait"
},
"Jennifer": {
"status":"Active"
},
"James": {
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
}';
$decode_data = json_decode($json_data);
foreach($decode_data as $key=>$value){
print_r($value);
}
Try:
$string = file_get_contents("/home/michael/test.json");
$json = json_decode($string, true);
foreach ($json as $key => $value) {
if (!is_array($value)) {
echo $key . '=>' . $value . '<br />';
} else {
foreach ($value as $key => $val) {
echo $key . '=>' . $val . '<br />';
}
}
}
More standard answer:
$jsondata = file_get_contents(PATH_TO_JSON_FILE."/jsonfile.json");
$array = json_decode($jsondata,true);
foreach($array as $k=>$val):
echo '<b>Name: '.$k.'</b></br>';
$keys = array_keys($val);
foreach($keys as $key):
echo ' '.ucfirst($key).' = '.$val[$key].'</br>';
endforeach;
endforeach;
And the output is:
Name: John
Status = Wait
Name: Jennifer
Status = Active
Name: James
Status = Active
Age = 56
Count = 10
Progress = 0.0029857
Bad = 0
Loop through the JSON with a foreach loop as key-value pairs. Do type-checking to determine if more looping needs to be done.
foreach($json_a as $key => $value) {
echo $key;
if (gettype($value) == "object") {
foreach ($value as $key => $value) {
# and so on
}
}
}
<?php
$json = '{
"response": {
"data": [{"identifier": "Be Soft Drinker, Inc.", "entityName": "BusinessPartner"}],
"status": 0,
"totalRows": 83,
"startRow": 0,
"endRow": 82
}
}';
$json = json_decode($json, true);
//echo '<pre>'; print_r($json); exit;
echo $json['response']['data'][0]['identifier'];
$json['response']['data'][0]['entityName']
echo $json['response']['status'];
echo $json['response']['totalRows'];
echo $json['response']['startRow'];
echo $json['response']['endRow'];
?>
Try it:
foreach ($json_a as $key => $value)
{
echo $key, ' : ';
foreach($value as $v)
{
echo $v." ";
}
}
When you decode a json string, you will get an object. not an array. So the best way to see the structure you are getting, is to make a var_dump of the decode. (this var_dump can help you understand the structure, mainly in complex cases).
<?php
$json = file_get_contents('/home/michael/test.json');
$json_a = json_decode($json);
var_dump($json_a); // just to see the structure. It will help you for future cases
echo "\n";
foreach($json_a as $row){
echo $row->status;
echo "\n";
}
?>
$json_a = json_decode($string, TRUE);
$json_o = json_decode($string);
foreach($json_a as $person => $value)
{
foreach($value as $key => $personal)
{
echo $person. " with ".$key . " is ".$personal;
echo "<br>";
}
}
The quickest way to echo all json values is using loop in loop, the first loop is going to get all the objects and the second one the values...
foreach($data as $object) {
foreach($object as $value) {
echo $value;
}
}
You have to give like this:
echo $json_a['John']['status'];
echo "<>"
echo $json_a['Jennifer']['status'];
br inside <>
Which gives the result :
wait
active
I am using below code for converting json to array in PHP,
If JSON is valid then json_decode() works well, and will return an array,
But in case of malformed JSON It will return NULL,
<?php
function jsonDecode1($json){
$arr = json_decode($json, true);
return $arr;
}
// In case of malformed JSON, it will return NULL
var_dump( jsonDecode1($json) );
?>
If in case of malformed JSON, you are expecting only array, then you can use this function,
<?php
function jsonDecode2($json){
$arr = (array) json_decode($json, true);
return $arr;
}
// In case of malformed JSON, it will return an empty array()
var_dump( jsonDecode2($json) );
?>
If in case of malformed JSON, you want to stop code execution, then you can use this function,
<?php
function jsonDecode3($json){
$arr = (array) json_decode($json, true);
if(empty(json_last_error())){
return $arr;
}
else{
throw new ErrorException( json_last_error_msg() );
}
}
// In case of malformed JSON, Fatal error will be generated
var_dump( jsonDecode3($json) );
?>

Json decode using content of array

I'm training myself (JSON and PHP) and I have a problem
I have Json decode look like this :
"playerstats": {
"steamID": "75068112",
"gameName": "ValveTestApp260",
"stats": [
{
"name": "total_kills",
"value": 2314497
},
{
"name": "total_deaths",
"value": 1811387
},
And to parse into php i do :
$url = 'myrul';
$content = file_get_contents($url);
$json = json_decode($content, true);
echo $json['playerstats']['stats'][1]['name']
And it works but the problem is when i change the id to get stats, the order of the array isn't the same :/
So i can't use [2] or any else number to get data.
I post here to know how could'i get stats using the attribute name of each array ('total_kills' for example) instead of [1]..[2]..
thanks for all your support
Use foreach and use if condition to check the name is 'total_kills' is true then store it into new array like this .
<?php
$json = json_decode($content, true);
$new_array =array();
$i=0;
foreach($json['playerstats']['stats'] as $row )
{
if($row['name']=='total_kills')
{
$new_array[]=array($row['name']=>$row['value']);
}
if($i<10)
{
break;
}
$i++
}
print_r($new_array);
?>
$url = 'myrul';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['playerstats']['stats'] as $row )
{
echo $row['name'];
echo $row['value'];
}
What you're looking for is a way to loop over the array. In PHP you can do the following;
$url = 'myurl';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json["playerstats"]["stats"] as $stat){
if($stat["name"] == "total_kills"){
echo "total kills: ".$stat["value"];
}
elseif($stat["name"] == "total_deaths"){
// ...
}
// etc... continue to select all parameters you would like
}
This will allow you to get the value for each stat with name using the if else statement.
Another way to do something with all objects in an array is to use the array_map() function, which takes another function as one of its arguments. Using this whenever you can will force you to adhere to good programming practices, because the passed in function cannot modify values outside of the array and arguments passed in via use.

SyntaxError: JSON.parse: unexpected character when parsing output from PHP

My php returns something as such:
if(!$result = $db->query($sql)){
echo $db->error;
die('There was an error running the query [' . $db->error . ']');
}
echo 'Total results: ' . $result->num_rows . "\n";
while($row = $result->fetch_assoc()){
echo json_encode($row);
echo "\n";
}
In my javascript, I want to put the output on the page if it's a json object or just log it to the console if it's something else:
var divOutput = function(output) {
try {
// var x = output.trim();
// x = JSON.parse(JSON.stringify(x));
var x = JSON.parse(output);
console.log(x);
$("#dbOut").html(JSON.stringify(x, null, '\t'));
} catch (e) {
console.log(output);
console.log(e);
}
}
var getPlayerByID = function() {
var myNumber = document.getElementById("PlayerInput").value;
$.ajax({
url : "db_funcs.php",
data : {
action : 'getPlayerByID',
a : myNumber,
},
type : 'post',
success : function(output) {
divOutput(output);
}
However it's throwing the JSON parse error when I query the database. How can I do this?
})
}
JSON must be output as a SINGLE monolithic json string. You're building multiple SEPARATE json strings, which is illegal syntax.
Consider JSON to be pretty much equivalent to the right-hand side of a javascript variable assignment:
var foo = this_part_is_json;
e.g. you need to have
var foo = [[stuff from row 1], [stuff from row2], etc...];
but are producing
var foo = [stuff from row1][stuff from row2];
^---syntax error would occur here
You need
$arr = array();
while($row = fetch from db) {
$arr[] = $row;
}
echo json_encode($arr);
It throws the error because you are not only echoing json.
In the line
echo 'Total results: ' . $result->num_rows . "\n"
You already echo something which is not json encoded.
With this code it should work:
//echo 'Total results: ' . $result->num_rows . "\n"; <---- this is not json
$arr = [];
while($row = $result->fetch_assoc()){
$arr[] = $row; //save each row in array
//echo "\n";
}
echo json_encode($arr); //encode all data as json
If you want the number of rows also in the json output add it in the $arr with a key like
$arr["num_rows"] = $result->num_rows;
This is wrong
while($row = $result->fetch_assoc()){
echo json_encode($row);
echo "\n";
}
Try like this
$arr = array();
while($row = $result->fetch_assoc()){
$arr[] = ($row);
}
echo json_encode($arr);
Use json_encode() only once, use arrays to store values in while()

Categories