I am trying to decode JSON
I am reading the JSON through STOMP. There are different JSON datasets so I need to work out which JSON dataset has come through. I do this by reading its title.
However there is one particular dataset I am having trouble reading
foreach (json_decode($msg->body,true) as $event) {
if(isset($event['schemaLocation'])) {
$schedule_id=($event['schedule']['schedule_start_date']);
$signalling_id=($event['schedule']['schedule_segment']['signalling_id']);
echo $schedule_id;
}
In the above example the isset function works fine and also $schedule_id obtains the right answer
However the $signalling_id gives an error of Undefined index:
Here is a dump of PART of the JSON (Its rather long............).The piece of JSON with the signalling_id is towards the end of the JSON. Any help to get the variable signalling_id much appreciated.
array(7) {
["schemaLocation"]=>
string(72) "http://xml.networkrail.co.uk/ns/2008/Train itm_vstp_cif_messaging_v1.xsd"
["classification"]=>
string(8) "industry"
["timestamp"]=>
string(13) "1410374918000"
["owner"]=>
string(12) "Network Rail"
["originMsgId"]=>
string(47) "2014-09-10T18:48:38-00:00vstp.networkrail.co.uk"
["Sender"]=>
array(3) {
["organisation"]=>
string(12) "Network Rail"
["application"]=>
string(4) "TOPS"
["component"]=>
string(4) "VSTP"
}
["schedule"]=>
array(11) {
["schedule_id"]=>
string(0) ""
["transaction_type"]=>
string(6) "Create"
["schedule_start_date"]=>
string(10) "2014-09-10"
["schedule_end_date"]=>
string(10) "2014-09-10"
["schedule_days_runs"]=>
string(7) "0010000"
["applicable_timetable"]=>
string(1) "N"
["CIF_bank_holiday_running"]=>
string(1) " "
["CIF_train_uid"]=>
string(6) "W64017"
["train_status"]=>
string(1) "1"
["CIF_stp_indicator"]=>
string(1) "O"
["schedule_segment"]=>
array(1) {
[0]=>
array(20) {
["signalling_id"]=>
string(4) "5Y75"
["uic_code"]=>
string(0) ""
["atoc_code"]=>
string(0) ""
["CIF_train_category"]=>
string(2) "EE"
["CIF_headcode"]=>
string(0) ""
["CIF_course_indicator"]=
............................................
schedule_segment is itself an array, so instead of
['schedule']['schedule_segment']['signalling_id']);
that should probably be
['schedule']['schedule_segment'][0]['signalling_id']);
As you can see in the var dump, signalling_id is inside another array. Use:
$signalling_id=($event ['schedule']['schedule_segment'][0]['signalling_id']);
If that one element array with key 0 is not constant throughout, you may need some logic to figure out what it is in each iteration.
Related
I'm getting a json response and have converted into array using json_decode.
var_dump gives the following:
array(1) {
["FlightInfoResult"]=>
array(2) {
["next_offset"]=>
int(1)
["flights"]=>
array(1) {
[0]=>
array(19) {
["ident"]=>
string(6) "AXB443"
["aircrafttype"]=>
string(4) "B738"
["filed_ete"]=>
string(8) "03:10:00"
["filed_time"]=>
int(1498358100)
["filed_departuretime"]=>
int(1498530900)
["filed_airspeed_kts"]=>
int(376)
["filed_airspeed_mach"]=>
string(0) ""
["filed_altitude"]=>
int(0)
["route"]=>
string(0) ""
["actualdeparturetime"]=>
int(0)
["estimatedarrivaltime"]=>
int(1498542900)
["actualarrivaltime"]=>
int(0)
["diverted"]=>
string(0) ""
["origin"]=>
string(4) "VOCI"
["destination"]=>
string(4) "OOMS"
["originName"]=>
string(26) "Cochin Int'l (Kochi Int'l)"
["originCity"]=>
string(20) "Kochi / Nedumbassery"
["destinationName"]=>
string(10) "Seeb Int'l"
["destinationCity"]=>
string(6) "Muscat"
}
}
}
}
I need to get the contents that comes within flights, ident:AXB443, etc..
I am not able to print any elements of the array.
This is multidimensional array. After json_decode you can get it via $variable['FlightInfoResult']['flights'][0]['ident'];
An variant on var_dump() is print_r(). This will give a simpeler, but in this case better to understand output.
I have a response for a zip code API. However, I cannot figure out how to the the value from 'place name' because of the space between the two words. No quite sure where to go from here.
object(stdClass)#1 (4) {
["post code"]=>
string(5) "42223"
["country"]=>
string(13) "United States"
["country abbreviation"]=>
string(2) "US"
["places"]=>
array(1) {
[0]=>
object(stdClass)#2 (5) {
["place name"]=>
string(13) "Fort Campbell"
["longitude"]=>
string(8) "-87.5585"
["state"]=>
string(8) "Kentucky"
["state abbreviation"]=>
string(2) "KY"
["latitude"]=>
string(7) "36.5995"
}
}
}
You need to put them inside a curly brace with a single quote:
$place_name = $response->places[0]->{'place name'};
echo $place_name;
Or as #scragar said in the comments, if you're not confortable accessing them thru objects, you can put a true flag on json_decode($response, true), so that you can access them as associative arrays instead.
Hello awesome programmers!
I am so sorry for the the novice question, however, I am having trouble finding a solution to my problem. I am attempting to run a for each loop through my array passed from my controller, however, the data being outputted is not the same as when I run a var_dump($array). I am thinking perhaps that I need to iterate through this object maybe? However, when I attempt to do so, I get a non-object error.
Controller:
$data['user_details'] = $this->ion_auth->user()->row();
View:
var_dump($user_details);
foreach($user_details as $item){
echo $item['email'];
}
The output of this is : "21nfn4111NR12" but should be roger#peterson.net!
I have also tried the object form:
var_dump($user_details);
foreach($user_details as $item){
echo $item->email;
}
However, it results in error trying to get property of non-object!
When I run the var dump I get the following:
object(stdClass)#21 (17) {
["id"]=>
string(1) "2"
["ip_address"]=>
string(14) "119.132.127.01"
["username"]=>
string(12) "roger petereson"
["password"]=>
string(40) "fdZxF/RQo4nZKmbA5XQlwefbc8f8e5c74899c3d0"
["salt"]=>
NULL
["email"]=>
string(19) "roger#peterson.net"
["activation_code"]=>
NULL
["forgotten_password_code"]=>
NULL
["forgotten_password_time"]=>
NULL
["remember_code"]=>
string(22) "44hjOlloLTIrkSrjSBVNie"
["created_on"]=>
string(10) "1404939094"
["last_login"]=>
string(10) "1405099607"
["active"]=>
string(1) "1"
["first_name"]=>
string(6) "Roger"
["last_name"]=>
string(5) "Peterson"
["is_owner"]=>
string(1) "1"
["user_id"]=>
string(1) "2"
}
The following line:
$this->ion_auth->user()->row();
returns an object not an array (check your var_dump output), so you just need to
echo $user_details->email;
I'm trying to get the values of a sub array out in a foreach loop.
I looked at this example as it seemed really relevant to my problem, but unfortunately I've not been able to get it to work, and I'm hoping someone here can pick up where I've gone wrong.
PHP foreach not working with sub-array
I have an array called $booked and inside that array I have a sub array $booked['30_booked'].
Within that second array there are multiple values, such as title, name, address etc.
My code currently looks like this:
foreach($booked['30_booking'] as $new_var){
var_dump('</br>', $booked['30_booking']);
var_dump('</br>', $new_var);
var_dump($new_var['title'], $new_var->title, $booked['30_booking']->title); exit();
}
I've output the data as you can see above in var_dump statements to try and get one of these methods to work.
Unfortunately nothing within $new_var is pulling out the title, but $booked['30_booking']->title
Have I not put it into the foreach statement correctly?
All help appreciated - thanks!
EDIT:
Main array output snippet:
array(6) { ["30_booked"]=> object(stdClass)#21 (34) { ["id"]=> string(2) "30" ["title"]=> string(2) "Ms" ["firstname"]=> string(5) "FIRST NAME" ["surname"]=> string(9) "LAST NAME" ["address"]=> string(6) "- -- -" ["postcode"]=> string(7) "FAK E99" ["country"]=> string(14) "United Kingdom" ["phone"]=> string(11) "01221111111" ["alt_phone"]=> string(0) "" ["email"]=> string(25) "fake#fake.co.uk" ["notes"]=> string(8) "FAKE DEAL" } }
EDIT 2:
Sub Array $booked['30_booking'] snippet:
object(stdClass)#21 (34) { ["id"]=> string(2) "30" ["title"]=> string(2) "Ms" ["firstname"]=> string(5) "FIRST NAME" ["surname"]=> string(9) "LAST NAME" ["address"]=> string(6) "- -- -" ["postcode"]=> string(7) "FAK E99" ["country"]=> string(14) "United Kingdom" ["phone"]=> string(11) "01221111111" ["alt_phone"]=> string(0) "" ["email"]=> string(25) "fake#fake.co.uk" ["notes"]=> string(8) "FAKE DEAL" }
EDIT 3:
My var_dump of the $new_var by itself is bringing back the value of the id - but when I try and get the second value out the sub array "title" it doesn't return anything.
FINAL FIX:
Thanks to Kita I realised I was returning a std class object and not a second array, something that I stupidly missed the first time round. Because of that I can't actually foreach on the object.
Which led me to this post which will help me fix the issue:
PHP foreach array with stdClass Object
Thank you very much for all your help!!!
You expected an array inside $booked['30_booking'] but in fact there was a stdClass object.
array(6) {
["30_booked"]=> object(stdClass)#21 (34) {
["id"]=> string(2) "30"
["title"]=> string(2) "Ms"
["firstname"]=> string(5) "FIRST NAME"
["surname"]=> string(9) "LAST NAME"
["address"]=> string(6) "- -- -"
["postcode"]=> string(7) "FAK E99"
["country"]=> string(14) "United Kingdom"
["phone"]=> string(11) "01221111111"
["alt_phone"]=> string(0) ""
["email"]=> string(25) "fake#fake.co.uk"
["notes"]=> string(8) "FAKE DEAL"
}
//I assume you have left out the other array elements from the Main array snippet.
}
Getting stdClass instead of array usually happens when you parse a JSON string with json_decode() without the second parameter.
// without second parameter
var_dump( json_decode( '{"id":"30"}' ) );
object(stdClass)#1 (1) {
["id"]=>
string(2) "30"
}
// 'true' as second parameter
var_dump( json_decode( '{"id":"30"}', true ) );
array(1) {
["id"]=>
string(2) "30"
}
Above examples are hosted at: http://ideone.com/GNMRlD
Since stdClass object itself does not provide iteration functionality, using it with foreach will yield errors.
You can convert stdClass into array with functions such as http://www.if-not-true-then-false.com/2009/php-tip-convert-stdclass-object-to-multidimensional-array-and-convert-multidimensional-array-to-stdclass-object/ .
For eg. if your array looks like below. foreach which I used will be working
$new_array = array(array('total'=>array('title'=>'test','text'=>'text')));
foreach ($new_array as $val)
{
print_r($val['total']['title']); // Use this for array
print_r($val->total->title); // Use this for object
}
if your array looks like below. Use the below foreach.
$new_array = array(array('total'=>array(array('title'=>'test','text'=>'text'),array('title'=>'test1','text'=>'text1'))));
foreach ($new_array as $val)
{
foreach($val['total'] as $new_val)
{
print_r($new_val['title']);
}
}
You can try this, I hope that helps you
foreach($booked as $new_var){
var_dump('</br>', $new_var);
var_dump('</br>',$new_var['30_booking']->title);
}
I think in your foreach there is mistake of word 30_booking
since in your main array out put display it shows 30_booked
check that also
I'm writing a PHP script to work with some JSON data. Below is an (abridged) var_dump($data). I want to return the value associated with ["[question(13), option(0)]"] which is 20. I can't figure out how to do it. I've tried $data->[question(13), option(0)] and $data->question(13). (I tried to look this up but I'm not sure what the notation means, so I'm not sure what I'm looking for)
object(stdClass)#133 (36) {
["id"]=>
string(1) "1"
["contact_id"]=>
string(0) ""
["status"]=>
string(8) "Complete"
["is_test_data"]=>
string(1) "0"
["datesubmitted"]=>
string(19) "2012-04-19 17:11:00"
["[question(5)]"]=>
string(11) "C. 40%, 40%"
["[question(9)]"]=>
string(47) "D. EBITDA and Free cash flow are the same thing"
["[question(10)]"]=>
string(48) "A. Accounts Payable as % of sales would increase"
["[question(11)]"]=>
string(20) "E. None of the above"
["[question(12)]"]=>
string(97) "A. A larger portion of initial investment is equity which can increase exit return potential."
["[question(13), option(0)]"]=>
string(2) "20"
["[url("embed")]"]=>
string(0) ""
["[variable("STANDARD_IP")]"]=>
string(13) "38.107.74.230"
["[variable("STANDARD_LONG")]"]=>
string(10) "-73.976303"
["[variable("STANDARD_LAT")]"]=>
string(9) "40.761902"
}
Either use extended object access notation:
$data->{'[question(13), option(0)]'}
Or just ask for normal array and use it as normal array.
json_decode($json, true);
try this
echo $data->{'[question(13), option(0)]'};