How to access elements in a JSON decoded associative array PHP - php

I'm new to php, and I'm wording how to return an associative array of JSON data type? So here's my php code:
$JSON = file_get_contents($url);
// echo the JSON (you can echo this to JavaScript to use it there)
//echo $JSON;
// You can decode it to process it in PHP
$data = json_decode($JSON,true);
var_dump($data);
Here's a snippet of what the data looks like when I dump it to the screen:
array(2) {
["product"] => array(1) {
[0]=> array(7) {
["styles"]=> array(13) {
[0]=> array(7) {
["price"]=> string(6) "$64.95"
["productUrl"]=> string(46) "http://www.zappos.com/product/7515478/color/25"
["percentOff"]=> string(2) "0%"
["styleId"]=> string(7) "1788226"
["imageUrl"]=> string(65) "http://www.zappos.com/images/z/1/7/8/8/2/2/1788226-p-DETAILED.jpg"
["color"]=> string(6) "Almond"
["originalPrice"]=> string(6) "$64.95"
}
Now how would I go about accessing the first array element?
I've tried:
echo $data[0][0]['orignalPrice'];
and it does not work. Could someone please help? Also is there a decent debugger for php on a mac? Appreciate any help.

Try that $data['product'][0]['styles'][0]['originalPrice']
Would also recommend you to have a look on a documentation, to learn more about arrays.

Related

PHP: how can I access JSON object

I'm sending this JSON:
[{"tipo":""},{"activo":""},{"titulo":"Servicoasd B"},{"texto":"asdasdasd"}]
to a php file via post method.
There, i do
$obj = json_decode($_POST['sentJson']);
However, I seem to be unable to access the elements of the JSON.
var_dump(($obj));
Shows the object:
array(4) {
[0]=>
object(stdClass)#2 (1) {
["tipo"]=>
string(0) ""
}
[1]=>
object(stdClass)#3 (1) {
["activo"]=>
string(0) ""
}
[2]=>
object(stdClass)#4 (1) {
["titulo"]=>
string(9) "Servico B"
}
[3]=>
object(stdClass)#5 (1) {
["texto"]=>
string(6) "asdasd"
}
}
But if I try
$obj['texto'];
$obj->{'texto'};
$obj[0]['texto'];
$obj[0];
It shows "undefined index texto" or "trying to get property of non object in" and the last one "Object of class stdClass could not be converted to string in". I'm very new to PHP, but still I can't seem to notice what I'm doing wrong. Any help would be appreciated.
Your JSON is a serialized array of four completely different objects, so when you run json_decode, that's what you get: an array.
If you want to access your objects inside that array, access them like you would any other indexed array:
$list = json_decode(...);
foreach($list as $obj) {
var_dump($obj)
}
Or target them explicitly using plain old numerical access.
$list = json_decode(...);
$last = $list[3];
$text = $last->texto;
But really the question you should be asking is why this is the JSON you get. An array with completely different objects at each position is terrible data, and should be fixed.

Accessing array with nested objects

I have an api wrapper i am using that returns something like this
object(stdClass)#7 (1) {
[0]=>
object(stdClass)#6 (2) {
["contactId"]=>
string(2) "nV"
["email"]=>
string(31) "email#domain.com"
}
}
how do i access the email part with PHP
Cast your API returned data to an array.
For example you are saving API returned data in $result variable. Cast it to an array.
$arrayResult = (array) $result;
echo $arrayResult[0]->email;
Try this.

How to loop through multidimensional array?

I'm currently getting a JSON response from a company's API and converting it into a PHP array like this:
$api_url = file_get_contents('http://example.com');
$api_details = json_decode($api_url, true);
When I run var_dump on $api_details, I am getting this:
array(2) {
["metadata"]=>
array(5) {
["iserror"]=>
string(5) "false"
["responsetime"]=>
string(5) "0.00s"
["start"]=>
int(1)
["count"]=>
int(99999)
}
["results"]=>
array(3) {
["first"]=>
int(1)
["result"]=>
array(2) {
[0]=>
array(4) {
["total_visitors"]=>
string(4) "3346"
["visitors"]=>
string(4) "3249"
["rpm"]=>
string(4) "0.07"
["revenue"]=>
string(6) "0.2381"
}
[1]=>
array(4) {
["total_visitors"]=>
string(6) "861809"
["visitors"]=>
string(6) "470581"
["rpm"]=>
string(4) "0.02"
["revenue"]=>
string(7) "13.8072"
}
}
}
}
I'm trying to do 2 things and can't figure out how to do either with a multidimensional array.
I need to check to see if metadata > iserror is false. If it is not false, I want to show an error message and not continue with the script.
If it is false, then I wants to loop through the results of results > result and echo the total_visitors, visitors, etc for each of them.
I know how to echo data from array, I guess I'm just getting confused when there's multiple levels to the array.
Anyone that can point me in the right direction would be much appreciated :)
You can iterate over arrays using foreach. You can read up on it here: http://php.net/manual/en/control-structures.foreach.php
Since you're using associative arrays, your code will look something like this:
if ($arr['metadata']['iserror']) {
// Display error here
} else {
foreach($arr['results']['result'] as $result) {
echo $result['total_visitors'];
echo $result['visitors'];
}
}
You'll have to tweak the code to fit exactly what you're doing, but this should get you over the line.
Hope that helps!

Decoding JSON string in PHP which has different headers

I am trying to decode a series of JSON messages
The JSON messgaes are received on an adhoc basis
If the JSON messages were all exactly the same format I would be fine. However they are not.
Here is an example of two different types.
object(stdClass)#11 (1) { ["SF_MSG"]=> object(stdClass)#12 (5) { ["time"]=> string(13) "1407962618000" ["area_id"]=> string(2) "NM" ["address"]=> string(2) "2B" ["msg_type"]=> string(2) "SF" ["data"]=> string(2) "FE" } }
object(stdClass)#13 (1) { ["CA_MSG"]=> object(stdClass)#14 (5) { ["to"]=> string(4) "0360" ["time"]=> string(13) "1407962618000" ["area_id"]=> string(2) "WH" ["msg_type"]=> string(2) "CC" ["descr"]=> string(4) "2S30" } }
One has a header of SF_MSG and the other CC_MSG
My question is "How do I in PHP distinguish between the different headers so I can read them in different ways
So for example echo '$Decodedjson->SF_MSG->time; will echo the time on the first one and
echo $Decodedjson->CC_MSG->to; will echo the to variable. However I need to know whether the header is SF_MSG or a CC_MSG before performing that task.
How do I read that Header title????? ie is it CC_MSG or SF_MSG ......$Decodedjson->?????
Thanks
EDIT
if ($con->hasFrame()){
$msg=$con->readFrame();
foreach (json_decode($msg->body) as $event) {
if(isset($event['SFG_MSG'])) {
$aid=($event->SF_MSG->area_id);
}
elseif(isset($event['CA_MSG'])) {
$aid=($event->CA_MSG->area_id);
}
echo $aid;
json_decode() requires true as the second parameter in order for the resultant object to be an associative array.
foreach (json_decode($msg->body, true) as $event)
once you do this, $event will be an associative array and no longer an object, so you will need to change the rest of your code to access $event as an array instead of an object.
// this won't work
$aid=($event->SF_MSG->area_id);
// change to this
$aid = $event["SF_MSG"]["area_id"];

Getting Data from PHP Array

I have this array that i used json_decode to create. This is my code:
$obj = json_decode($json);
$results = $obj->{"results"}; // This selects the results section
echo $results[artistName];
$results is the array
The array looks like this:
array(1) {
[0]=> object(stdClass)#5 (8) {
["wrapperType"]=> string(6) "artist"
["artistType"]=> string(6) "Artist"
["artistName"]=> string(5) "Human"
["artistLinkUrl"]=> string(56) "https://itunes.apple.com/us/artist/human/id35761368?uo=4"
["artistId"]=> int(35761368)
["amgArtistId"]=> int(1173165)
["primaryGenreName"]=> string(3) "Pop"
["primaryGenreId"]=> int(14)
}
}
But it does not echo anything. Please help.
It's still an object, so you need to access the key like this.
echo $results[0]->artistName;
echo $results[0]->artistName
Notice, u have array of stdClasses

Categories