PHP JSON not decoding properly - php

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.

Related

add column to json php

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";
}

how to retrieve multiple array json with php

i know it sounds so easy. just use foreach looping or json_decode, and you can retrieve json data.
yeah it was, until i got multiple array json when trying retrieving data from elasticsearch.
im confused how to retrieve this :
{
"took":3,
"status": "taken",
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total":2,
"msg":"ilusm",
"hits":
[
{
//goes here
"id":1234
},
{
//goes here
"id":4321
}
]
},
"date-created": "2016-06-06"
}
i use this to retrieve my first data :
$result = json_decode(json_encode($product),true);
echo "total took:";
echo $result['took'];
echo "total shards:";
echo $result['_shards']['total'];
the problem is,i cant retrieve data inside hits.
how can i retrieve hits id : 1234 ?
echo"view all total hits :";
echo $result['hits']['total'];
echo"view all total msg:";
echo $result['hits']['msg'];
echo"view hist data :";
echo json_decode(json_encode($result['hits']['hits']), true);
i got this error :
Message: Array to string conversion
please help me to fix this out.
many thanks in advance.
Try this it's work for me.
$result= '{"took":3,"status": "taken","_shards": {"total": 5,"successful": 5,"failed": 0},"hits": {"total":2,"msg":"ilusm","hits":[{"id":1234},{"id":4321}]},"date-created": "2016-06-06"}';
$array= json_decode($result, true);
echo $array["hits"]["hits"][0]['id']; //output 1234
output : 1234
$string = '{"took":3,"status": "taken","_shards": {"total": 5,"successful": 5,"failed": 0},"hits": {"total":2,"msg":"ilusm","hits":[{"id":1234},{"id":4321}]},"date-created": "2016-06-06"}';
$hits= json_decode($string, true);
$hits = $hits['hits']['hits'];
foreach($hits as $hitsIndex => $hitsValue){
if($hitsValue["id"] == '1234'){
var_dump($hitsValue["id"]);
}
}
I think you are a little confused about json & php data management.
Should you tell us what $product variable is? (string,object/array).
Usually you get json data as string and parse it to php variables with json_decode.
Your Javascript-like object declaration of $product is useless.

Split JSON data and only get the variables names

I am making an CMS, Where you have to put in your own JSON data string.
Like this
Then its going to a php file. But in that file I want to split the data string
from something like this:
{"main_object": {"audio":"nl", "title":"Opdracht 1", "vraag":"[0, 1, "a"]", "antwoord"["yes", "no", 0]" }}
to this
["audio", "title", "vraag", "antwoord"]
Using json_decode, care, your JSON string is not correct :
$json_string = '{"main_object": {"audio":"nl", "title":"Opdracht 1", "vraag":[0, 1, "a"], "antwoord":["yes", "no", 0]}}';
// Add TRUE to force an array, not an object
$array = json_decode($json_string, TRUE);
print_r(array_keys($array['main_object']));
It works with this code. I tried.
Assuming the following PHP code:
<?php
$JSONData = '{"main_object": {"audio":"nl", "title":"Opdracht 1", "vraag":"[0, 1, "a"]", "antwoord"["yes", "no", 0]" }}'; //In reality you'll be getting the JSON data from the form rather than assigning it here.
$arrayData = json_decode($JSONData, true);
if ($arrayData !== null
&& is_array($arrayData)
&& isset($arrayData["main_object"])
&& is_array($arrayData["main_object"])) { //JSON was valid and in the correct format
$usableData = array_keys($arrayData["main_object"]);
//Do whatever you need to do with your $usableData
} else {
//Handle badly formatted data here.
}

PHP - Extracting an array (object?) from a JSON file

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

json response handling issue

I'm stuck with retrieving json response below is the json output. Your help would be highly appreciated.
{ "productHeader" : { "totalHits" : 684 }, "products" : [ { "name" : "Victoria Hotels", "productImage" : { "url" : "http://hotels.com/hotels/9000000/8640000/8633700/8633672/8633672_20_b.jpg" }, "language" : "en", "description" : "Location. Victoria Hotels is in Foshan (Nanhai) and area attractions include Renshou Temple and New Plaza Stadium. Additional regional attractions include Guangdong Folk Art Museum and Bright Filial Piety Temple.", "identifiers" : { }, "fields" : [ { "name" : "regions2", "value" : "Guangdong" },
Please help me to fetch the particular values. For example if I need to fetch the name, image url from the json response.
You can use json_decode to parse a JSON string to an array and access it's values:
// assuming, that $string contains the json response
// second parameter to true, to get an array instead of an object
$data = json_decode( $string, true );
if ( $data ) {
echo $data['products'][0]['name'];
// or whatever value
} else {
echo 'JSON could not be parsed, error: ' . json_last_error();
}
To show all values in the products array, simple loop it:
if ( $data ) {
foreach($data['products'] as $product){
echo $product['name'];
}
// or whatever value
} else {...
If you're going to use PHP to get the values, check this:
$decodedJson = json_decode($json, true);
print_r($decodedJson);
You will get an array, to get image source and other tags you need to do it in a loop or select concrete index like:
echo $decodedJson['productHeader']['products'][0]['productImage']['url'];
In JS you should extract the values the same way.

Categories