Getting elements from an array with contents from decode json - php

It's sort of hard to describe the question in the title, but I will explain it in the body. So I have this example JSON (It's similar to the one I have):
[{"AssetId":234234,"Name":"Test1"},{"AssetId":53453,"Name":"Test2"}]
So basically I want to get the AssetId element from the first array of the main array. I am calling this in PHP, but it isn't working
$array = json_decode("[{"AssetId":234234,"Name":"Test1"},{"AssetId":53453,"Name":"Test2"}]");
echo $array[0][0]
So I guess that would be the first array in the main array to get AssetId of the element with the Name of Test1. Any help on getting it?

Try replacing the double quotes with single quotes, your attempt will lead to parse error of unexpected T_STRING
Instead of this
$array = json_decode("[{"AssetId":234234,"Name":"Test1"},{"AssetId":53453,"Name":"Test2"}]");
^
Try this:
$array = json_decode('[{"AssetId":234234,"Name":"Test1"},{"AssetId":53453,"Name":"Test2"}]');
foreach($array as $arr){
echo $arr->AssetId;
}

what about echo $array[0]->AssetId
edit :
$json = json_decode('[{"AssetId":234234,"Name":"Test1"},{"AssetId":53453,"Name":"Test2"}]');
echo $json[0]->AssetId;
works here

Related

Get value from Array inside of an Array

I have the following string output if I run print_r($val):
{"next_offset":-1,"records":[{"id":"e3266222-5389-11ed-ab30-0210c01ad3d2","name":"That is a nice name"}]}
Now, I need the value of attribute "id". Sounds simple but I'm not able getting there.
Does something like this work?
I'm assuming $val is a json string.
<?php
$val = "{\"next_offset\":-1,\"records\":[{\"id\":\"e3266222-5389-11ed-ab30-0210c01ad3d2\",\"name\":\"That is a nice name\"}]}";
$val = json_decode($val);
print_r($val->records[0]->id);
?>

PHP Array inside of an array issue

I'm having some problems getting the data through my PHP loop.
<?php
$url = 'https://www.fibalivestats.com/data/1653309/data.json';
$content = file_get_contents($url);
$json = json_decode($content, true);
?>
<?php
foreach($json['totallds']['sPoints'] as $item); {
echo $item;
}
?>
The error I'm getting is an array to string conversion error. What I'm trying to get is the data from the sPoints array that will give me a Top 5 points scorers for a basketball game.
I'll build a table for this in HTML later but for now, it's not displaying the data at all and I'm getting errors. I feel like I may have confused arrays and strings too. Any thoughts about what I'm doing wrong? JSON file can be found in the $url variable.
Also if it helps, here's the link to where I have gotten the data from and what context the Top 5 is from https://www.fibalivestats.com/u/NSS/1653309/lds.html
Thanks!
Your $item is an array, so you can't just echo it like that. You can, however, echo its columns, for example:
foreach($json['totallds']['sPoints'] as $item) {
echo $item['firstName'] . ' ' . $item['familyName'];
}
Notice the removed semicolon between the foreach () and {.
Well, array to string conversion error means you're trying to echo an array.
If you see the return of the url you are looking at, you can verify that the "sPoints" key returns an array with several objects.
Try to change echo to print_r or var_dump to view entire data or complete your business logic.
Try changing:
echo $item;
to:
var_dump($item);

Read nested json in php

I know others have already asked about this, but I don't find a solution for my problem. In my PHP page I call an external service and I can't modify the response obtained.
I'm moving my first steps both with JSON and PHP.
The response is a JSON like this, I print this using the var_dump method:
object(stdClass)#1 (3)
{
["search_string"]=>string(15) "ABCDEFG HI LMNO"
["resut"]=>string(5) "apixi"
["0"]=>array(1){
[0]=>object(stdClass)#2(2){
["resp_code"]=>string(7) "12.34.0"
["resp_description"]=>string(15) "ABCDEFG HI LMNO"
}
}
}
In my PHP page I can read the value ”ABCDEFG HI LMNO” for the key "search_string" with this code, in the $output variable I store the result of the cUrl call
.......
$output = curl_exec($ch);
$jsonDecode =json_decode(str_replace('""','"',$output));
var_dump($jsonDecode);
echo $jsonDecode -> search_string;
I need the str_replace method because the JSON is dirty but not always, how can I access at the fields "resp_code" and "resp_description" and then store them in a variable? I tried many solutions but none works for me.
Instead of converting JSON array to stdClass object you can also convert it to regular PHP array by adding second parameter to the json_decode function:
$jsonDecode =json_decode(str_replace('""','"',$output), true);
In your case in the output, you'll get a multidimensional array.
Then, to access resp_code and resp_description, you can do something like this:
$respCode = $jsonDecode[0]["resp_code"];
$respDescription = $jsonDecode[0]["resp_description"];
In the decoded JSON you have, the resp_code and resp_description keys are difficult to get to, because the top-level object has a numerical ("0") attribute. Trying to reach that attribute like this:
$jsonDecode -> 0
will give this parsing error:
syntax error, unexpected '0' (T_LNUMBER), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'
Trying the same with a string notation (-> "0") also fails.
However, the suggestion in the error message is useful: encapsulate the zero with braces. Then you can proceed easily by adding the array index selector ([0]) to get to the object and keys of your interest, like this:
echo $jsonDecode->{0}[0]->resp_code;
echo $jsonDecode->{0}[0]->resp_description;
If you expect more elements in that array $jsonDecode->{0}, then loop over them like this:
foreach ($jsonDecode->{0} as $element) {
echo $element->resp_code;
echo $element->resp_description;
}
Alternative
If, however, you prefer to work with associative arrays instead of objects, you can use the second argument of json_encode as stated in the docs:
assoc
When TRUE, returned objects will be converted into associative arrays.
So then you would pass true as second argument:
$jsonDecode = json_decode(str_replace('""', '"', $output), true);
The above code would then be rewritten like this to access the variable as an associative array:
foreach ($jsonDecode[0] as $element) {
echo $element["resp_code"];
echo $element["resp_description"];
}

php issue accessing array

I have the following code :
$results = $Q->get_posts($args);
foreach ($results as $r) {
print $r['trackArtist'];
}
This is the output :
["SOUL MINORITY"]
["INLAND KNIGHTS"]
["DUKY","LOQUACE"]
My question is, if trackArtist is an array, why can't I run the implode function like this :
$artistString = implode(" , ", $r['trackArtist']);
Thanks
UPDATE :
Yes, it is a string indeed, but from the other side it leaves as an array so I assumed it arrives as an array here also.
There must be some processing done in the back.
Any idea how I can extract the information, for example from :
["DUKY","LOQUACE"]
to get :
DUKY, LOQUACE
Thanks for your time
It's probably a JSON string. You can do this to get the desired result:
$a = json_decode($r['trackArtist']); // turns your string into an array
$artistString = implode(', ', $a); // now you can use implode
It looks like it's not actually an array; it's the string '["DUKY","LOQUACE"]' An array would be printed as Array. You can confirm this with:
var_dump($r['trackArtist']);
To me content of $r['trackArtist'] is NOT an array. Just regular string or object. Instead of print use print_r() or var_dump() to figure this out and then adjust your code to work correctly with the type of object it really is.

Help Decoding JSON

I'm trying to get the "screenshotUrls" string from this piece of json:
$request_url = 'http://itunes.apple.com/search?term=ibooks&country=us&entity=software&limit=1';
$json = file_get_contents($request_url);
$decode = json_decode($json, true);
echo $decode['results'][0]['screenshotUrls'];
But I get only text "Array"
What have I done wrong?
Try
var_dump($decode['results'][0]['screenshotUrls']);
IF you get 'Array' output by PHP that means that you're trying to echo an actual array (or the string 'Array'...). That means you need to get a specific index value.
Since $decode['results']['0']['screenshotUrls'] is an array, if you want just a string (say, delimited by commas), you could use
echo implode(",", $decode['results']['0']['screenshotUrls']);
This will iterate over the array, and return a comma-separated string of all the URLs.
Do a var_dump($decode['results']['0']['screenshotUrls']). You'll find that the ['screenshotUrls'] is actually an Array, containing one or more URLs (hence the plural 'urls' in its name).
There's nothing wrong with your code so far, but $decode['results'][0]['screenshotUrls'] is an array of all the URLs to screenshots. To go through each one individualy, you need to do:
forearch ($decode['results'][0]['screenshotUrls'] as $url) {
// Do stuff here
}

Categories