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);
Related
I'm inserting value with implode and get this type json
[
{
"id":"1",
"f_name":"Mitrajit",
"l_name":"Samanta",
"class":"XII",
"section":"A,B,C",
"roll":"1",
"status":"1"
}
]
but I want this type :-
[
{
"f_name" : "Mitrajit",
"l_name" : "Samanta",
"class" : "XII",
"section": ["A","B","C"],
"roll" : "1",
"status" : "1"
}
]
how can I get "A,B,C" to ["A","B","C"]?
You need to use json_decode() to converting json to php array. Then select section value in json array and use explode() to converting it to array. At the end convert php array to json using json_encode()
$json = json_decode($jsonStr, true);
$json[0]["section"] = explode(",", $json[0]["section"]);
$jsonStr = json_encode($json);
Check result in demo
This question already has answers here:
PHP multidimensional array search by value
(23 answers)
Closed last year.
So I have the following JSON Object as an example:
{
"employees": {
"employee300": {
"number" : "example",
"Name" : "example",
"position" : 1
},
"employee456": {"number" : "example",
"Name" : "example",
"position" : 2},
"employee120":{"number" : "example",
"Name" : "example",
"position" : 3}
}
}
I only have the position and I want to get the employee's id. For example, I have the position number that is 2 and I need to get the id that is "employee456".
I know there are a lot of key functions in PHP, but I would like to know how I can make my code work in my scenario.
I can also convert the json to an array if there is a solution to it that way.
I'm not sure whether you want to do this in JS or PHP, going to assume the latter.
<?php function get_employee_at_pos($employees, $pos)
{
foreach ($employees as $key => $value) {
if ($value['position'] == $pos) {
return $key;
}
}
return false;
}
use var keys = Object.keys(obj) to get the keys, then use the myobject[keys[1]]. (1 corresponds to position - 1).
EDIT: in php
$keys = array_keys(myobject); and use $myobject[$keys[1]]
EDIT 2: in php, you need to load the json in an array
$myjson = json_decode(file_get_contents("yourfile.json"), true); // loads yourfile.json and converts to a php array.
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.
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.
It's stored inside MongoDB and passed to my view file with json_decode.
Using PHP, how can I grab the values from within?
"environment" : {
"_id" : "QU",
"name" : "QA Unstable",
"streams" : "unstable",
"hosts" : [
"deployclient1",
"deployclient2"
]
}
Use $array = json_decode($json_string, TRUE);. Second variable makes it array if you supply TRUE or object if you omit it.
Now to actually answer the question since you already know of json_decode:
Using PHP, how can I grab the values from within?
json_decode will evaluate the JSON string into a object in PHP (by default) which means you can use basic dynamic accession syntax to get to your values, i.e. to get _id:
$object->environment->_id;
Or a host:
$object->environment->hosts[0]
That will return: deployclient1
Don't forget to wrap the string in curly braces...
$str = '{"environment" : {
"_id" : "QU",
"name" : "QA Unstable",
"streams" : "unstable",
"hosts" : [
"deployclient1",
"deployclient2"
]
}}';
print_r(json_decode($str, true));