Json decode using content of array - javascript

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.

Related

I have nested while loop php mysql. how to encode it to valid JSON

<?php
// header("Access-Control-Allow-Origin: *");
// header("Content-Type: application/json; charset=UTF-8");
require_once ('connection.php');
try {
$selectCatagory = 'select Catagory_id, Catagory_name, Catagory_image from district_shop.catagory';
$prepareCatagory = $conn -> prepare($selectCatagory);
$prepareCatagory ->execute(array());
while ($fetchCatagory = $prepareCatagory ->fetch(PDO::FETCH_ASSOC)) {
$Catagory = $fetchCatagory['Catagory_id'];
$selectSubCatagory = 'select * from district_shop.subcatagory where Catagory_id= :Cat_id';
$prepareSubCatagory = $conn -> prepare($selectSubCatagory);
$prepareSubCatagory -> execute(array(
'Cat_id' => $Catagory
));
while ($fetchSubCatagory = $prepareSubCatagory -> fetch(PDO::FETCH_ASSOC)) {
//print_r($fetchSubCatagory);
echo json_encode($fetchSubCatagory);
// It doesnot encoded to valid JSON
}
}
} catch (PDOException $th) {
$th-> errMessage();
}
?>
// The outpuut invalid JSON file is as :-
[{"Subcatogory_id":"1","Subcatagory_name":"Crasher Material","Subcatagory_description":"Crasher Material","Active_Subcatagory":"Active","Catagory_id":"1"},{"Subcatogory_id":"2","Subcatagory_name":"Plumbing Items","Subcatagory_description":"Plumbing Items","Active_Subcatagory":"Active","Catagory_id":"1"},{"Subcatogory_id":"3","Subcatagory_name":"Iron Material","Subcatagory_description":"Iron Material","Active_Subcatagory":"Active","Catagory_id":"1"},{"Subcatogory_id":"4","Subcatagory_name":"Cementing","Subcatagory_description":"Cement Material","Active_Subcatagory":"Active","Catagory_id":"1"},{"Subcatogory_id":"5","Subcatagory_name":"Marble & Tiles","Subcatagory_description":"Marble & Tiles","Active_Subcatagory":"Active","Catagory_id":"1"},{"Subcatogory_id":"6","Subcatagory_name":"Electric Material","Subcatagory_description":"Electric Material","Active_Subcatagory":"Active","Catagory_id":"1"}][{"Subcatogory_id":"7","Subcatagory_name":"Sweets ","Subcatagory_description":"Sweets ","Active_Subcatagory":"Active","Catagory_id":"2"},{"Subcatogory_id":"8","Subcatagory_name":"Salted(Namkeen)","Subcatagory_description":"Salted(Namkeen)","Active_Subcatagory":"Active","Catagory_id":"2"},{"Subcatogory_id":"9","Subcatagory_name":"Cold and Beverages","Subcatagory_description":"Cold and Beverages","Active_Subcatagory":"Active","Catagory_id":"2"},{"Subcatogory_id":"10","Subcatagory_name":"Food and Snacks","Subcatagory_description":"Food and Snacks","Active_Subcatagory":"Active","Catagory_id":"2"}]
Sir, I am unable to create its valid json as i have two tables in mySQL named catagory and subcatagory.
so nested while loop is used to extract subcatagory by using catagory. The output is encoded in json but it was no a valid JSON.
The problem is you're echoing multiple JSONs without nesting them properly. Instead of this:
[subcat1, subcat2, subcat3][subcat4, subcat5, subcat6] (invalid)
Your output should look like be one of these
[subcat1, subcat2, subcat3, subcat4, subcat5, subcat6] (valid flat array)
[[subcat1, subcat2, subcat3], [subcat4, subcat5, subcat6]] (valid nested arrays)
In your code, you should harvest responses into an array, which you echo json_encode() in the end.
...
$output = [];
while ($fetchCatagory ...) {
...
while ($fetchSubCatagory ...) {
// for nested array
$output[] = $fetchSubCatagory;
// for flat array
$output = array_merge($output, $fetchSubCatagory);
}
}
echo json_encode($output);
That should do the trick :-)

Parsing SQL array data to php mail()

I'm doing an SQL SELECT to retrieve client data to then generate an email from.
The $param that is being parsed to the API is an object:
var param = {
delivery_id: "string",
order_id: "string",
}
The order_id is then being used to query a second table:
$param = $_REQUEST['param'];
$param = json_decode($param);
$collname = "orders";
$sql = 'SELECT * FROM '.$collname.' WHERE `id` = '.$param->order_id;
$result = $conn->query($sql);
//$conn is defined externally, and is not the cause of the problem
$aData = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$aData[] = $row;
}
sendEmail($aData);
} else {
echo "Error";
}
mysqli_close($conn);
This first query makes perfect sense, and when the $aData is being returned to the front end as a string, it looks like expected; an array of objects (one object).
But when I try to access it in the sendEmail function, it can't access the key values. Same when I try to echo json_encode($aData[0]->id) (doesn't work) instead of just echoing json_encode($aData[0]) (works).
The email is actually sent to the hard-coded BCC-mail, but without any of the values within the array.
function sendEmail(&$aData){
$to = $aData[0]->contact_email;
$subject = "".$aData[0]->id;
$txt = "Something something ".$aData[0]->contact.",
something something.
";
$headers = "From: email#email.com" . "\r\n" .
"BCC: email#email.com";
mail($to,$subject,$txt,$headers);
}
How do I access the object keys in the API?
EDIT: question answered by S.DEV. Since data was returned as associative array and not an object, correct targeting syntax was $aData[0]['id'].
You can try as following:
while($row = $result->fetch_assoc()) {
//$aData[] = $row;
sendEmail($row);
}
//function sendEmail(&$aData){
function sendEmail($aData){

PHP to JSON Array Output is Wrong

What I am trying to do doesn't feel difficult, but for some reason I can't seem to find the correct way to ouput this JSON array, from php.
PHP code:
$a = array();
$i=0;
while($row = mysqli_fetch_array($result))
{
$i++;
$a = array();
$epoch = $row['time'];
$dt = new DateTime("#$epoch"); // convert UNIX timestamp to PHP DateTime
$a = array(
"time" => $dt->format('Y-m-d H:i:s'),
"signal" => $row['signal'],
"symbol" => $row['symbol'],
"price" => $row['price'],
"timeframe" => $row['timeframe'],
"epoch" => $row['time']);
echo json_encode($a, JSON_UNESCAPED_SLASHES);
}
Output:
{
"time":"2016-11-14 17:23:00",
"signal":"Sell",
"symbol":"XAUUSDecn",
"price":"1221.64000",
"timeframe":"M1",
"epoch":"1479144180"
}
{
"time":"2016-11-14 17:07:59",
"signal":"Sell",
"symbol":"GBPJPYecn",
"price":"135.13200",
"timeframe":"M1",
"epoch":"1479143279"
}
The correct output should have },{ NOT }{ between each object.
What I am ultimately trying to do:
function getTrades(a) {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "core/engine.php",
data: "q=data&account="+a,
dataType: "html", //expect html to be returned
success: function(response){
if(response=="nologin") {
alert("Sorry, but either your account is not activated or your login is incorrect!");
} else {
var j = $.parseJSON(response);
$.each(j, function (k, v) {
$("#trades").html('<span class="tradesignal"><!-- span class="signalarrowup"></span-->'+v.time+'<span style="color:#2DC14E;"> '+v.signal+'</span>   <button class="tsym" id="sym_'+v.epoch+'">'+v.symbol+'</button>  '+v.price+'  '+v.timeframe+'</span>');
});
}
//alert(response);
console.log(response);
}
});
}
Each {json},{json} object will have its data printed into a span on an html page.
Appreciate the guidance!
Try creating a results array and push each one of the objects there, then after the loop finishes, convert the array to json and print it.
example:
$results = array();
$i = 0;
while($row = mysqli_fetch_array($result)){
//your code here
$a = array("time" => ....);
$results[] = $a; //this will add $a to $results
}
echo json_encode($results, JSON_UNESCAPED_SLASHES);
Just to add a little more explanation in addition to the code the other answers are suggesting. The problem is, you aren't outputting a JSON array. Each time you do
echo json_encode($a, JSON_UNESCAPED_SLASHES);
inside your loop, you output a valid JSON object like:
{
"time":"2016-11-14 17:23:00",
"signal":"Sell",
"symbol":"XAUUSDecn",
"price":"1221.64000",
"timeframe":"M1",
"epoch":"1479144180"
}
However, when you output the subsequent objects, getting a result like
{
"time": ...
}
{
"time": ...
}
You no longer have valid JSON. Even though each of the individual objects is valid, concatenating them together isn't. Simply adding a comma between the objects will still not make it valid. In order to produce an actual JSON array, the comma separated objects will need to be enclosed in square brackets like this:
[
{
"time": ...
},
{
"time": ...
}
]
That's why you need to add each of the arrays you're creating in the loop to an outer array and then json_encode the whole thing after the loop. The outer PHP array will become the outer JSON array you need.
As Xorifelse said, you want to put the data in an array, and then call json_encode on the array. Here is a code that should work:
$a = array();
$i=0;
while($row = mysqli_fetch_array($result))
{
$i++;
$epoch = $row['time'];
$dt = new DateTime("#$epoch"); // convert UNIX timestamp to PHP Date
$a[] = array("time" => $dt->format('Y-m-d H:i:s'), "signal" => $row['signal'], "symbol" => $row['symbol'], "price" => $row['price'], "timeframe" => $row['timeframe'],"epoch" => $row['time']);
}
echo json_encode($a, JSON_UNESCAPED_SLASHES);

jQuery/Ajax - Post is not returning multiple results [duplicate]

This question already has answers here:
JSON encode MySQL results
(16 answers)
Closed 1 year ago.
I've spent a couple of hours looking through several the similar answers before posting my problem.
I'm retrieving data from a table in my database, and I want to encode it into a JSON. However, the output of json_encode() is only valid when the table has one single row. If there is more than one row, the test at http://jsonlint.com/ returns an error.
This is my query:
$result = mysql_query($query);
$rows = array();
//retrieve and print every record
while($r = mysql_fetch_assoc($result)){
$rows['data'] = $r;
//echo result as json
echo json_encode($rows);
}
That gets me the following JSON:
{
"data":
{
"entry_id":"2",
"entry_type":"Information Relevant to the Subject",
"entry":"This is my second entry."
}
}
{
"data":{
"entry_id":"1",
"entry_type":"My Opinion About What Happened",
"entry":"This is my first entry."
}
}
When I run the test at http://jsonlint.com/, it returns this error:
Parse error on line 29:
..."No comment" }}{ "data": {
---------------------^
Expecting 'EOF', '}', ',', ']'
However, if I only use this first half of the JSON...
{
"data":
{
"entry_id":"2",
"entry_type":"Information Relevant to the Subject",
"entry":"This is my second entry."
}
}
... or if I only test the second half...
{
"data":{
"entry_id":"1",
"entry_type":"My Opinion About What Happened",
"entry":"This is my first entry."
}
}
... the same test will return "Valid JSON".
What I want is to be able to output in one single [valid] JSON every row in the table.
Any suggestion will be very much appreciated.
The problem is you're spitting out separate JSON for each row, as opposed to doing it all at once.
$result = mysql_query($query);
$rows = array();
//retrieve and print every record
while($r = mysql_fetch_assoc($result)){
// $rows[] = $r; has the same effect, without the superfluous data attribute
$rows[] = array('data' => $r);
}
// now all the rows have been fetched, it can be encoded
echo json_encode($rows);
The minor change I've made is to store each row of the database as a new value in the $rows array. This means that when it's done, your $rows array contains all of the rows from your query, and thus you can get the correct result once it's finished.
The problem with your solution is that you're echoing valid JSON for one row of the database, but json_encode() doesn't know about all the other rows, so you're getting a succession of individual JSON objects, as opposed to a single one containing an array.
You need to change your PHP code into something like this:
$result = mysql_query($query);
$rows = array();
//retrieve every record and put it into an array that we can later turn into JSON
while($r = mysql_fetch_assoc($result)){
$rows[]['data'] = $r;
}
//echo result as json
echo json_encode($rows);
I think you should do
$rows = array();
while($r = mysql_fetch_assoc($result)){
$rows[]['data'] = $r;
}
echo json_encode($rows);
echo should be placed outside of the loop.
I was trying the same in my PHP, so I came whit this...
$find = mysql_query("SELECT Id,nombre, appaterno, apmaterno, semestre, seccion, carrera FROM Alumno");
//check that records exist
if(mysql_num_rows($find)>0) {
$response= array();
$response["success"] = 1;
while($line = mysql_fetch_assoc($find)){}
$response[] = $line; //This worked for me
}
echo json_encode($response);
} else {
//Return error
$response["success"] = 0;
$response["error"] = 1;
$response["error_msg"] = "Alumno could not be found";
echo json_encode($response);
}
And, in my Android Class...
if (Integer.parseInt(json.getString("success")) == 1) {
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
if (!value.equals(1)) {
JSONObject jsonArray = (JSONObject) value;
int id = jsonArray.getInt("Id");
if (!db.ExisteAlumo(id)) {
Log.e("DB EXISTE:","INN");
Alumno a = new Alumno();
int carrera=0;
a.setId_alumno(id);
a.setNombre(jsonArray.getString("nombre"));
a.setAp_paterno(jsonArray.getString("appaterno"));
a.setAp_materno(jsonArray.getString("apmaterno"));
a.setSemestre(Integer.valueOf(jsonArray.getString("semestre")));
a.setSeccion(jsonArray.getString("seccion"));
if(jsonArray.getString("carrera").equals("C"))
carrera=1;
if(jsonArray.getString("carrera").equals("E"))
carrera=2;
if(jsonArray.getString("carrera").equals("M"))
carrera=3;
if(jsonArray.getString("carrera").equals("S"))
carrera=4;
a.setCarrera(carrera);
db.addAlumno(a);
}
}
} catch (JSONException e) {
// Something went wrong!
}
}
I must have spent 15 hours on this issue. Every variation discussed above was tried. Finally I was able to get the 'standard solution' working. The issue, very oddly, appears to be this:
When the interval is set beyond 14 hours, json appears to be unable to parse it. There must be a limit to JSON.
$sql= "SELECT cpu_name, used, timestamp FROM tbl_cpu_use WHERE timestamp>(NOW() - INTERVAL 14 HOUR) ORDER BY id";
$result=mysql_query($sql);
if ($result){
$i=0;
$return =[];
while($row = mysql_fetch_array($result, MYSQL_NUM)){
$rows[] = $row;
}
echo json_encode($rows);
}else{
echo "ERROR";
}

Converting data returned from mysql query to json(tree based)

This question has been asked earlier too, but no body has answered I guess.
Lets say mysql query returns result like following
name | id
tarun | 1
tarun | 2
tarun | 3
Now If we do standard json encode, I will get some thing like below:
[{"name":"tarun","id":"1"},{"name":"tarun","id":"2"},{"name":"tarun","id":"3"}]
But I was output something like below
[{"name" : "tarun", "ids" : [{"id": "1"},{"id": "2"},{"id": "3"}]}]
Please ignore my syntax mistakes (if any), But I hope my ques makes sense.
I am using PHP as my backend scripting language.
You're probably doing something like
SELECT name, id FROM ...
and
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
Given your desired structure, you'd want
$data[$row['name']]['ids'][] = array('id' => $row['id']);
This won't give you your exact structure, but it would be put all the ids as a child-array beneath an array keyed by the tarun field value.
Extending #Marc B's answer
// Getting per person id's list
$people = array();
while ($row = mysql_fetch_assoc($result)) {
$people[$row['name']][] = array('id' => $row['id']);
}
// Encoding as JSON
$output = "[";
foreach ($people as $name => $ids) {
$output .= '{"name" : "'.$name.'", ids: [';
foreach ($ids as $key => $id) {
$output .= '{"id" : "'.$id.'"},';
}
rtrim($output, ",");
$output .= ']},';
}
rtrim($output, ",");
$output .= ']';
echo $output;
The solution above is specific to the question. A generic JSON Encode method for this problem in my opinion is very tough or not possible.
I suggest to do the query with orderying by name, then when you read the rows, just do a simple check to see if the $row['name'] has changed, if so add the id's youve collected to the php object.
$curName="";
$curIds=array();
$betterJ=array();
$result = mysql_query ("SELECT name,id FROM mytable WHERE 1 ORDER BY NAME);
while($row=mysql_fetch_array($result)
{
if($curName=="")
$curName=$row['name']
if($row['name']!=$curName){
$betterJ[]=array($name=>$curName,$ids=>$Ids)
$curName=$row['name']
$curIds=array()
}
$Ids[]=$row['id];
}
$betterJ[]=array($name=>$curName,$ids=>$Ids);
echo json_encode($betterJ);
this might have a typo or something since I wrote it here, but it should produce json like
[ [name:"tarus1",ids:[1,2,3]], [name:"tarus2",ids:[4,5,6], ... ]
which you would work great in a template in html etc.

Categories