Multidimensional Array Information Grabbing - php

I have an array that looks as such:
{
"stocks": {
"0": {
"name": "Stock Exchange",
"current_price": 12843.973,
"available_shares": 0,
},
"1": {
"acronym": "TSBC",
"current_price": 503.106,
"available_shares": 171252632,
"benefit": {
"requirement": 4000000,
"description": "Entitled to receive occasional dividends"
}
},
and from number 1, I need to grab current_price. I have a foreach that grabs it from both, but I'm not sure how to only grab the info from number 1, being the second block of information - TSBC. Any ideas?

As you added the json tag to your question, I must note that you have presented an invalid json content. There is unexpected comma right after the number 0 within the first "stocks" object "available_shares": 0,.
So let's remove that comma and if we talk about "multidimensional array" let's decode our json string into associative array with json_decode function in such way:
// $str - is some part of your json string
$str = '{
"stocks": {
"0": {
"name": "Stock Exchange",
"current_price": 12843.973,
"available_shares": 0
},
"1": {
"acronym": "TSBC",
"current_price": 503.106,
"available_shares": 171252632,
"benefit": {
"requirement": 4000000,
"description": "Entitled to receive occasional dividends"
}
}}}';
$arr = json_decode($str, true);
// now we are able to get 'current_price' from the second element of array
var_dump($arr['stocks'][1]['current_price']);
// the output:
float 503.106

Related

JSON Parsing Error: Warning: Attempt to read property on array

am trying to parse this JSON from a Football API using PHP.
Below is a subset of the JSON output.
Specifically, I am trying to retrieve the “45%” value from the "home" element from the below json.
$json = '{
"get": "predictions",
"parameters": {
"fixture": "198772"
},
"errors": [],
"results": 1,
"paging": {
"current": 1,
"total": 1
},
"response": [{
"predictions": {
"winner": {
"id": 1189,
"name": "Deportivo Santani",
"comment": "Win or draw"
},
"win_or_draw": true,
"under_over": "-3.5",
"goals": {
"home": "-2.5",
"away": "-1.5"
},
"advice": "Combo Double chance : Deportivo Santani or draw and -3.5 goals",
"percent": {
"home": "45%",
"draw": "45%",
"away": "10%"
}
}
}]
}';
I have tried the following codes but it does not work
$response = json_decode($json);
echo 'Output: '. $response->response->predictions->percent->home;
The error i am getting is:
Warning: Attempt to read property "predictions" on array in C:\xampp\htdocs\xampp\livescore\api-test\predictions.php on line 93
I also tried this but no luck.
echo 'Output: '. $response->response[0]->predictions[0]->percent[0]->home;
appreciate any help or insights I can get.
thanks in advance.
Whenever you see a [ in a json (or any other) object, it's the start of an array, and to reach a child of that array you have to reference it's index (postition). For what you want, this would do it.
$response = json_decode($json);
echo 'Output: '. $response->response[0]->predictions->percent->home;
"response": [{ shows the beginning of an array, and since there's only one item in the array (starting with {) you can reference it by it's index 0. If there were many items in the array, you could loop over them, like
$response->response.forEach(arrayItem => {
// arrayItem is the current element in the array you're looping though
})
You've probably missed that only value of "response" is an array, which has dictionary inside.
Try this: $response->response[0]->predictions->percent->home

How to get a specific value from a json array out of a list of arrays

everyone, I was just trying to find out a way to get the value of a link from a JSON array , after I have searched the array with help of Id. I am using PHP's file_get_contents and the webpage from which information is to be taken looks like
[{
"id":"2972",
"name": "AbC",
"link":"any link",
"epg": "any link",
"dur": "disabled",
"language": "y",
"category": "TOP 100",
"logo": "any url here"
},
{
"id": "1858",
"name": "Efg",
"link": "url",
"epg": "url",
"dvr": "disabled",
"language": "E",
"category": "TOP 100",
"logo": "url"
}]
From here suppose I have been given an Id 1858 so I have to find a link from the array of Id having 1858
I am a beginner in PHP and was just fidgeting around with a piece of code and tried to get its solution and a big Thanks To You For Your Answer and valuable Time.
if you are using file_get_contents('php://input'); then you should try this to access json data
$json = file_get_contents('php://input'); //get json data in variable
$array = json_decode($json); //parse json data in php array
// assecc the array with use of foreach loop
foreach($array as $obj){
//access the json element here like $id = $obj->id; $url = $obj->link;
//if you want to check the id value in array you can compare value with if condition
$id = $obj->id;
// find link for specific id
if($id =='1858'){
$url = $obj->link;
echo $url; // do something with link
//you can use break; statement if you found your element and terminate the loop
}
}
You can use array_column, to map pairs of json keys/values:
<?php
$json ='
[
{
"id": 3,
"link": "http:\/\/example.com\/3"
},
{
"id": 5,
"link": "http:\/\/example.com\/5"
}
]';
$data = json_decode($json, true);
if($data !== null) {
echo array_column($data, 'link', 'id')[5] ?? null;
}
Output:
http://example.com/5
To understand this we can see the result of array_column.
var_export(array_column($data, 'link', 'id'));
Output:
array (
3 => 'http://example.com/3',
5 => 'http://example.com/5',
)
So with the above code, we are checking for and outputting the associated index of 5 (the original id).

PHP - Deleting an element of a JSON array changes the array syntax

I can successfully delete elements of a JSON array with PHP, but I cannot understand why the JSON array changes syntax after deleting an element that's not the last one.
So, here's my User.json file:
[
{
"id": "kS79BhPx"
},
{
"id": "ycC7km7A"
},
{
"id": "hgF5D4es"
}
]
Here's my delete.php script:
$className = "Users";
// get the index
$index = (int)$_GET['index'];
//fetch data from json
$data = file_get_contents($className. '.json');
$data_array = json_decode($data, true);
// delete the row with the index
unset($data_array[$index]);
//encode back to json
$data = json_encode($data_array, JSON_PRETTY_PRINT);
file_put_contents($className. '.json', $data);
So, if I go to the following URL, just to test my php function:
https://example.com/delete.php?index=0
The script successfully deletes the first element of the JSON array, but then it changes into this:
{
"1": {
"id": "ycC7km7A"
},
"2": {
"id": "hgF5D4es"
}
}
Instead, if I set https://example.com/delete.php?index=2 - so I want to delete the last array's element - it saves it as follows:
[
{
"id": "kS79BhPx"
},
{
"id": "ycC7km7A"
}
]
This last result is what I need to achieve all the times I delete an element because I need the JSON array syntax to stay as [...], not as {...}.
What am I doing wrong in my PHP script?
Using unset() on an array (associative or not) in PHP will preserve the existing keys making the array associative. You need to reindex the array after using unset():
// delete the row with the index
unset($data_array[$index]);
$data_array = array_values($data_array);

Accessing value inside multi-dimension JSON array using PHP

I read several posts on here and have been unable to find success in resolving the problem I am having.
I am trying to figure out how to get the NAME field from the UploadImage array.
I have the following JSON being passed to me from a Webhook.
{
"$version":5,
"Entry":{
"Number":"11",
"Order":null,
"Origin":
{
"City":"Portland",
"CountryCode":"US",
}
,
"Message":"the message",
"UploadImage":[
{
"ContentType":"image/png",
"Id":"F-lMbiCYdwiYS8ppkQS4gsyE",
"Name":"Screen.png",
"Size":55907
}
],
"Subject":"here is the subject"
}
I have no problem grabbing the value of Subject or Message, but I cannot figure out how to grab the NAME within UploadImage.
$contact = json_decode($json);
$subject=$contact->{'Subject'};
When I do
$uploadimage=$contact->{'UploadImage'};
it just writes out ARRAY.
I can do
echo $contact->{'Entry'}->{'Number'};
and it works, so it has to be something with the bracket being there before the curly bracket. I know this has to be something simple that I am missing.
Any help is GREATLY appreciated.
$uploadimage=$contact->{'UploadImage'}[0]->{'Name'};
Firstly try
$contact = json_decode($json, true);
Adding the second argument returns an array instead of an object which will make things easier. Objects with numerical keys are troublesome... Now you can,
print_r($contact);
to see exactly what you've got. I imagine that
echo $contact['UploadImage'][0]['Name'];
Will get you what you're looking for.
Notice that UploadImage contains an array of objects (or an array of arrays after conversion).
another solution is:
$contact = json_decode($text);
$name = '';
foreach($contact->UploadImage as $k=>$v){
foreach($v as $k2=>$v2){
echo $k2.' - '.$v2.'<br />';
if($k2=='Name'){ $name = $v2;}
}
};
var_dump($name);
//response
ContentType - image/png
Id - F-lMbiCYdwiYS8ppkQS4gsyE
Name - Screen.png
Size - 55907
//name
string 'Screen.png' (length=10)
Have you try to use like below:
$uploadimage=$contact->UploadImage[0]->Name;
In JSON the square braces [] mark an array section and the curly braces {} mark an object. In your JSON string UploadImage is an array, which contains a single object.
Try changing your JSON as follows:
{
"$version": 5,
"Entry": {
"Number": "11",
"Order": null,
"Origin": {
"City": "Portland",
"CountryCode": "US"
},
"Message": "the message",
"UploadImage": {
"ContentType": "image/png",
"Id": "F-lMbiCYdwiYS8ppkQS4gsyE",
"Name": "Screen.png",
"Size": 55907
},
"Subject": "here is the subject"
}
}

Get JSON objects in PHP, not array

Im writing a website in php that gets a JSONstring from another php-api Ive created.
The string looks like this:
{
"result": "true",
"results": {
"20": {
"id": "20",
"desc": "a b ct tr",
"active": "1",
"startdate": "2013-04-03",
"starttimehour": "18",
"starttimemin": "0",
"enddate": "2013-04-03",
"endtimehour": "22",
"endtimemin": "0",
"creator": "a"
},
"21": {
"id": "21",
"desc": "test",
"active": "0",
"startdate": "2013-04-04",
"starttimehour": "18",
"starttimemin": "0",
"enddate": "2013-04-04",
"endtimehour": "22",
"endtimemin": "0",
"creator": "a"
}
}
}
Ive found lots of answers on how to get information from a JSONarray but Im not using an array here.
So the question is: how can I get the objects that are labeled 20, 21 and so forth(These numbers are generated by the server so I dont know which ones will be returned).
Or should I rewrite how my api returns the JSON as an array instead. Something like this:
{"result"="true", "results":[{...},{...},{...}]}
$json = json_decode($json_string, True);
foreach($json['results'] as $key => $value) {
// access the number with $key and the associated object with $value
echo 'Number: '.$key;
echo 'Startdate: '.$value['startdate'];
}
I suppose that you are getting the json by POST without any parameter, like
curl http://someapi.somedomain/someresource/ -X POST -d #data.json
so basically
$data = file_get_contents('php://input');
$object = json_decode($data);
print_r($object);
should solve your problem. and $object will be your json object that you post.
You do get the JSON response as a string. That's just the way JSON works. To "convert" the data to a format and structure that is easily accessible, you can use a PHP function called json_decode().
You have two choices when using the function -
To convert the data into an array. json_decode($jsonString,true)
If you use this method, you would access the data like you would for an associative array. $jsonArray['results']['21']
To convert the data into an object. json_decode($jsonString)
With this method, you would use object notation to traverse the data -
$num = 21;
$jsonObj->results->$num
First you decode the string($string) then you can loop through it and get all the properties of the objects. Remember that accessing properties is with ->prop instead of ['prop']. This way you do not have to deal with it in an array manner.
$jsoned = json_decode($string);
foreach($jsoned->results as $o) {
foreach($o as $key => $value) {
echo "The key is: ".$key." and the value is: ".$value."<br>";
}
}
Working example what will print out:
Key is: id and value is: 20
Key is: desc and value is: a b ct tr
Key is: active and value is: 1
etc...

Categories