Get specific data in variable array JSON with jQuery PHP - php

I'm trying to get specific data from a JSON file (url) and save that data in a PHP variable.
The JSON comes from an url. For example:
https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/Viducius?api_key=secret
The JSON file:
{
"viducius": {
"id": 26541044,
"name": "Viducius",
"profileIconId": 591,
"revisionDate": 1480517139000,
"summonerLevel": 30
}
}
So my question is how can I get the data from id, in this case 26541044, and put that into a PHP variable?
Also to get the data from the JSON file, I have to search for the id while the array name 'viducius' came from a PHP variable.
TLDR:
The array $arrayName contains an id '26541044' that has to be saved into variable $id
Is there someone who can help me with this? I was thinking on doing this in jQuery but if it's easier with PHP only thats fine too.

That is a JSON String, therefore you need to convert it into a PHP data structure. PHP Provides json_decode() to do that.
$json_string = '{"viducius": {
"id": 26541044,
"name": "Viducius",
"profileIconId": 591,
"revisionDate": 1480517139000,
"summonerLevel": 30
}
}';
$obj = json_decode($json_string);
$id = $obj->viducius->id;
echo 'id = ' . $id;

Related

Get JSON Data From .json (php)

i'm trying to get the fields "name, price, image and rarity" to show in a php file, anyone can help me? Thanks ;D
{
"status": 300,
"data": {
"date": "2019-09-16T00:00:00.000Z",
"featured": [
{
"name": "Flying Saucer",
"price": "1,200",
"images": {
"icon": icon.png",
},
"rarity": "epic",
},
I'm using this that a friend told me, but i cant put that to work :c
<?php
$response = json_decode(file_get_contents('lista.json'), true);
foreach ($response as $val) {
$item = $val['name'];
echo "<b>$item</b>";
}
?>
I'm not quite sure what you are trying to achieve. You can just access the contents via the $response array like this:
echo $response['status']; // would output 300
You can use foreach to iterate through the array. For example: If you want to output the name of every element of the array you can use:
foreach ($response['data'] as $val) { // loop through every element of the data-array (if this makes sense depends on the structure of the json file, cant tell because it's not complete)
echo $val['featured']['name'];
}
You gotta get the index in $val['data']['featured']['name'] to retrieve the name index.
When you defined the second parameter of json_decode, you said that you want your json to be parsed to an array. The brackets in the original json identify when a new index of your parsed array will begin.
I suggest you to read about json_decode and json in general:
JSON: https://www.json.org/
json_decode function: https://www.php.net/manual/en/function.json-decode.php

How to fetch an Array from MySQL with PHP

In my database I have POSTed following JSON with REST API:
{
"author": "Someone",
"hero_name": "Iron Man",
"hero_desc": ["Iron", "Man"],
}
Now in database Table, the entry says only Array for the hero_desc.
I cannot figure out how to get the actual items in that array.. for example to fetch Iron from hero_desc.
Here is how it gets returned with GET request:
{
"id": "11",
"user_id": "1",
"author": "Someone",
"hero_name": "Iron Man",
"hero_desc": "Array",
}
I am quite new to PHP so I am worried that I would need to mess up my whole app architecture to get this to work. I though PHP can handle fetching arrays by default if it sees it's an JSON Array.
use json_decode(); function for change json to array
$json_to_array = json_decode($your_json_variable_name);
You could change array data to JSON with json_encode In one hand you have an array without the key that code makes a number key for that in another hand if have an array with the key you can get that inside JSON with that key.
$content ='your content or your array data';
header('Content-Type: application/json; charset=utf8');
echo json_encode($content);

Cant Grab data in API due to array

So it is pretty simple but I am having some difficulty.
I am grabbing data from an API and echoing it to the page using PHP and it is working.
However, not when the API data is wrapped in an 'array' or '[]'.
API 1: (WORKING)
{
"data": 18,
"data2": 20,
}
API 2: (NOT WORKING)
[
{
"data": 18,
"data2": 20,
}
]
My PHP code:
<?php
$url = "my correct url is here";
$json = json_decode(file_get_contents($url), true);
$dataprint = $json["data"];
echo $dataprint;
?>
Why is the simple change of '[]' messing the code up and not allowing me to print the information?
The square brackets are JSON notation for an array 'without' keys (In the decoded php array keys are numeric start with 0, and don't skip any numbers). You can access the data if you adjust one line in your code (add [0]):
$dataprint = $json[0]["data"];

How to create a JSON array in php?

I am trying to create a simple android application that takes data from a database and displays it in a list format on the android screen. I made a php script that queries the database and returns a json object. I convert the json object into json array and extract the relevant data for display. But I am getting this error "JSONException: type org.json.JSONObject cannot be converted to JSONArray".
Following is my php script -
// response Array
$response = array("tag" => $tag, "success" => 0, "error" => 0);
$username = $_POST['username'];
$events = $db->viewAttendingEvent($username);
if ($events) {
$response["success"] = 1;
$response["event"]["owner"] = $events["owner"];
$response["event"]["friendsnames"] = $events["friendsnames"];
$response["event"]["vote"] = $events["vote"];
$response["event"]["accepted"] = $events["accepted"];
$response["event"]["eventname"] = $events["eventname"];
$response["event"]["eventnumber"] = $events["eventnumber"];
$response["event"]["created_at"] = $events["created_at"];
echo json_encode($response);
This is the json which I receive back :
{
"tag": "view_invitations",
"success": 1,
"error": 0,
"event": {
"owner": "jkkkkoopp",
"friendsnames": "don",
"vote": "0",
"accepted": "f",
"eventname": "yyy",
"eventnumber": "11",
"created_at": "2014-05-29 22:27:31.843528"
}
}
I am trying to extract 'event' from this json object, which is not an array.
it should be
{
"event": [
{
"owner": "jkkkkoopp",
"friendsnames": "don",
"vote": "0",
"accepted": "f",
"eventname": "yyy",
"eventnumber": "11",
"created_at": "2014-05-2922: 27: 31.843528"
}
]
}
Can someone help me how to make this a valid jsonArray ? Thanks
If you're looking to get a JavaScript 'Array' (from which I mean an Object with nothing but integer keys) then you need to only have integer keys in your PHP Array.
This article is a pretty good resource and explains some of the differences between arrays and objects in javascript. The relevant quote here comes from the What Arrays Are section (emphasis mine):
Javascript arrays are a type of object used for storing multiple
values in a single variable. Each value gets numeric index and may be
any data type.
No it should not be what you proposed it should be. If that were the case you would have to have your php be this:
$response["event"][0]["owner"] = $events["owner"];
$response["event"][0]["friendsnames"] = $events["friendsnames"];
$response["event"][0]["vote"] = $events["vote"];
$response["event"][0]["accepted"] = $events["accepted"];
$response["event"][0]["eventname"] = $events["eventname"];
$response["event"][0]["eventnumber"] = $events["eventnumber"];
$response["event"][0]["created_at"] = $events["created_at"];
The way you have it now is event is an associative array so it converts it to an object. You are expecting that event = an array of objects. So you need to either change your php code to make event be an array of objects (as demonstrated above) or you need to modify your expectations to have event = an object.

Manipulating data from a JSON feed to display it

{
"Group": [
{
"name": "HolderOne",
"operators": [
{
"username": "ken",
"status": 3
},
.....etc.....
The JSON feed I am attempting to manipulate has to format above.
I wish to be able to display username and status.
$json = file_get_contents("urlhere");
$obj=json_decode($json);
echo $obj->username;
echo $obj->status;
This obviously doesn't work as they are nested(?) within the feed...I have tried:
$obj->Group[0]->name->operators->username
and
$obj->Group[0]->name->username
to no avail (as well as json_decode with ,true and ['name'], etc).
Am I being particularly dim?
when I do a var dump, the data is being collected from the feed okay.
The best way to figure this out is to iteratively do print_r's:
print_r($obj)
//prints what you see above
print_r($obj['Group']
//prints the Group Object
print_r($obj['Group'][0])
//prints first element in Group Object
print_r($obj['Group'][0]['operators'])
//etc.....
That's how I find out how to access these deep elements if I get a little stuck. Though it appears to me that you want:
$obj->Group[0]->operators[0]->username

Categories