I do an SQL query that I execute. The result is in the variable : $result = $req->fetchAll();
After this I do : echo json_encode($result); and I get :
[{"date":"2022","0":"2022","title":"KKKK","1":"KKKK","test":"haha","2":"haha"}]
But now I would like to add a field named n to every element of my json. So for example I will now get :
[{"date":"2022","0":"2022","title":"KKKK","1":"KKKK","test":"haha","2":"haha", "n" : "12", "3":"12"}]
i tried several things but it doesn't work. For example I tried the following before encoding :
foreach($result as &$row) {
$row->n = "12";
}
Related
I am looking to make a multi line graph from this example.
Instead of using data from a CSV file I'm building an array of values from the database:
$token_prices = sw::shared()->prices->getForTokenID($token_id);
$token_prices_array = array();
foreach ($token_prices as $token_price) {
$token_prices_array[] = [
"date" => $token_price['date'],
"close" => $token_price['close']
];
}
$second_token_prices = sw::shared()->prices->getForTokenID(3);
$second_token_prices_array = array();
foreach ($second_token_prices as $second_token_price) {
$second_token_prices_array[] = [
"date" => $second_token_price['date'],
"close" => $second_token_price['close']
];
}
$all = array_merge($second_token_prices_array, $token_prices_array);
foreach ($all as $datapoint) {
$result[$datapoint['date']] []= $datapoint['close'];
}
Data output:
{"15-Jun-18":["8.4","0.14559"],"16-Jun-18":["8.36","0.147207"],"17-Jun-18":["8.42","0.13422"],"18-Jun-18":["8.71","0.146177"],"19-Jun-18":["8.62","0.138188"],"20-Jun-18":["8.45","0.128201"],
My issue is with plugging the data from the database in:
var tokendata = <?php echo json_encode($result) ?>;
data = tokendata;
data.forEach(function(d) {
d.date = parseTime(d.date);
d.close = +d.close;
d.open = +d.open;
});
I get an issue here "data.forEach is not a function"...
How can I fix this to use the data from the database?
Here is the Fiddle
It looks like you are embedding the results of the query php page as a JSON string -- if you want to iterate over that data as an array, you will have to parse it back into a Javascript object first.
I'm assuming that the first code snippet is running on a different server, and so the $result array is not directly available to your javascript code -- is this why you are trying to set a variable to the encoded return value? If so, it's not the best way to pull data into your page's script, but this may work for you:
var data = JSON.parse('<?php echo json_encode($result)?>');
or even:
var data = eval(<?php echo json_encode($result)?>);
Both methods assume that your result is returned as a valid json string, since there is no error checking or try/catch logic. I honestly don't know what the output of the json_encode() method looks like, so if you still can't get it working, please update your post with an example of the returned string.
I've got a JSON file and I want to access the contents via PHP. The problem is accessing an array inside the JSON file. Other methods suggested on this site don't seem to work. An example of the JSON structure is at the bottom. The PHP code here is the only PHP code between my opening and closing PHP tags.
This PHP code works. I'm accessing something that isn't an array.
$jsondata = file_get_contents('BFZ.json');
$data = json_decode($jsondata, true);
$id = $data['name'];
echo $id;
This doesn't work. I'm trying to access the "name" portion of the "cards" array (object?) in the JSON file.
$jsondata = file_get_contents('BFZ.json');
$data = json_decode($jsondata, true);
$id = $data['cards']['name'];
echo $id;
This also doesn't work:
$id = $data['cards']['name'][0];
The structure of the JSON file with example info:
"name" : "Nemesis",
"code" : "NMS",
"gathererCode" : "NE",
"oldCode" : "NEM",
"magicCardsInfoCode" : "ne",
"releaseDate" : "2000-02-14",
"border" : "black",
"type" : "expansion",
"block" : "Masques",
"onlineOnly" : false,
"booster" : [ "rare", ... ],
"cards" : [ {}, {}, {}, ... ]
The structure of the "cards" array (object?) of the JSON file with example info:
"name" : "Sen Triplets",
"manaCost" : "{2}{W}{U}{B}",
"cmc" : 5,
"colors" : ["White", "Blue", "Black"],
"type" : "Legendary Artifact Creature — Human Wizard",
"supertypes" : ["Legendary"],
"types" : ["Artifact", "Creature"],
"subtypes" : ["Human", "Wizard"],
"rarity" : "Mythic Rare",
"text" : "At the beginning of your upkeep, choose target opponent.
This turn, that player can't cast spells or activate
abilities and plays with his or her hand revealed.
You may play cards from that player's hand this turn.",
"flavor" : "They are the masters of your mind.",
"artist" : "Greg Staples",
"number" : "109",
"power" : "3",
"toughness" : "3",
"layout" : "normal",
"multiverseid" : 180607,
"imageName" : "sen triplets",
"id" : "3129aee7f26a4282ce131db7d417b1bc3338c4d4"
I got the JSON file from here: http://mtgjson.com/ . The file references the card game Magic: the Gathering. I'm using PHP because my intention is to eventually load the data into a MySQL database.
It looks like cards key holds an array of json objects. json_decode() will parse it as such.
Given that, $data['cards'][0]['name'] should give you the name of first card. Analogically, $data['cards'][1]['name'] should give you name of the second card.
The $data['name'] you were targeting was the one from the extension.
You need to access the array ['cards'] to reach the card list then with a loop you can get all the cards name.
you might want to do that :
$jsondata = file_get_contents('http://mtgjson.com/json/BFZ.json');
$data = json_decode($jsondata, true);
$cards = $data['cards'];
$cardsName = array();
foreach ($cards as $card) {
$cardsName[] = $card['name'];
}
var_dump($cardsName);
This will create an array will all the cards name
You need to unserialize your data
$jsondata = file_get_contents('http://mtgjson.com/json/BFZ.json');
$data = unserialize($jsondata);
// Show the unserialized data;
var_dump ($data);
I have JSON data being fed in which I have set manually for debugging purposes. I'm trying to get the data to be stored in to their own variables (for later DB storage), however, they are empty.
I have tried 2 different things yet it's still appearing as empty when echo'ing them out. Is there a better way of doing this and one that will actually store the data in the required variables?
$json = '[{
"q1":"a",
"q2":"d"
}]';
$questions = json_decode($json, true);
$q1 = $questions->q1; //first method of getting the data
$q2 = $questions['q2']; //second attempted method
echo "q1: ".$q1;
echo "q2: ".$q2;
Get rid of the square braces around the json string:
$json = '{
"q1":"a",
"q2":"d"
}';
$questions = json_decode($json, true);
$q1 = $questions['q1']; //first method of getting the data
$q2 = $questions['q2']; //second attempted method
echo "q1: ".$q1;
echo "q2: ".$q2;
Edit: Since you are planning on sending the information over AJAX, say using something like
JSON.stringify($('#formId').serializeArray());
you may end up with an JSON array, as per your original post. In that case, you may want to do a for loop, or access the question directly like so:
$json = '[{
"q1":"a",
"q2":"d"
}]';
$questions = json_decode($json, true);
foreach($questions as $question) {
$q1 = $question['q1']; //first method of getting the data
$q2 = $question['q2']; //second attempted method
}
// This would also work:
echo $questions[0]['q1'];
I'm trying top decode this JSON data with PHP, but it's not returning anything:
{ "message" : "",
"result" : [ { "Ask" : 0.040400209999999999,
"BaseVolume" : 456.53976963999997,
"Bid" : 0.040200010000000001,
"Created" : "2014-12-19T03:48:49.13",
"High" : 0.044610999999999998,
"Last" : 0.040400199999999997,
"Low" : 0.037999999999999999,
"MarketName" : "BTC-XPY",
"OpenBuyOrders" : 194,
"OpenSellOrders" : 520,
"PrevDay" : 0.042073039999999999,
"TimeStamp" : "2014-12-30T02:45:32.983",
"Volume" : 11072.491576779999
} ],
"success" : true
}
This is what I have so far:
$pricejson = file_get_contents('https://bittrex.com/api/v1.1/public/getmarketsummary?market=btc-xpy');
$price = json_decode($pricejson, true);
echo $price->result->Last;
When I open the php file containing this code, there's nothing. If I use echo $pricejson, I get the whole thing printed out so I definitely have the data.
What is wrong?
The second argument to json_decode forces all objects to be parsed as associative arrays so you need to access it with array notation. Additionally result is an array always so you need to loop over it or access it by index:
$price = json_decode($pricejson, true);
// print the first price
echo $price['result'][0]['Last'];
// print all prices:
foreach ($price['result'] as $data) {
echo $data['Last'];
}
Or if you want a mix of objects/arrays then:
$price = json_decode($pricejson);
echo $price->result[0]->Last;
// print all prices:
foreach ($price->result as $data) {
echo $data->Last;
}
In top of this its possible there is a json parse error. You might also need to make sure that the JSON you get back is being parsed properly.
{
"firstName":"sunny",
"religion": {"holly":"1",
"bolly":"colly",
"nolly":"only"
},
"lonely":"money",
"ronney":"leone",
"honey":"bunny"
}
This is my JSON. I want to get all the data from this and to be stored into some php variables or an array.
I Used the following code to extract data from my JSON. I decoded it first and then stored it in an array..
$val_array = json_decode($jsondata, true);
echo $jsondata;
$AAA = $val_array->firstName;
$BBB = $val_array->religion;
$CCC_id = $val_array->bolly;
$DDD = $val_array->nolly;
$CCC_id = $val_array->lonely;
$DDD = $val_array->ronney;
But it didn't give me any output. Then I used this.
foreach($data['val_array'] as $item)
{
echo $item[0];
}
}
No output. Help??
You get this second param wrong:
$val_array = json_decode($jsondata, true);
$AAA = $val_array['firstName'];
OR
$val_array = json_decode($jsondata, false);
$AAA=$val_array->firstName;
Your JSON is not valid. Remove commas after last elements:
{
"firstName" : "sunny",
"religion" : {
"holly" : "1",
"bolly" : "colly",
"nolly" : "only" # Here
},
"lonely" : "money",
"ronney" : "leone",
"honey" : "bunny" # And here
}
You have an error in your JSON :
"nolly":"only",
"honey":"bunny",
remove the ',' at the end of these 2 lines, then json_decode() will return you an array.
And if you want an object, do not pass second argument to json_decode()
json_decode by default returns an object yet since you are setting the second parameter to true, you are given an associative array with the information instead.
It basically comes down to the fact that either you do not need to fill in the second parameter and get the object you want, or you work with arrays when you set the parameter to true.
A little reading on PHP.net will do you good for further reference since their documentation is well presented, usually commented by others with helpful suggestions and quite clean as well!
$val_array = json_decode($jsondata, true);
$m1=$val_array['firstName'];
$m2=$val_array['lonely'];
$m3=$val_array['ronney'];
$m4=$val_array['honey'];
$m4=$val_array['religion']['holly'];
$m5=$val_array['religion']['bolly'];
$m6=$val_array['religion']['nolly'];
BY using this, we don't have to use foreach loops or inner loops for accessing data. Viola!