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
Related
So, I am returning 2 different multi-dimensional arrays from 2 separate db calls.(Can't use a join because of our specific API for db calls)
I need to search through 2nd array and if a value matches that of a value in the first array, I need to append the related data to that row in first array for display in datatable. I have tried numerous things to just get the values to show. Here is what my arrays look like and where I am at with it.
Array 1
{"status":"SUCCESS","message":"Successfully read","data":
[{"ordnbr":"12345",
"custid":"CUSTID #",
"custname":"My Customers Name",
"custordnbr":"54321",
"slsperid":"ID",
"orddate":"2015-05-14",
"shipdate":"2015-06-03",
"dtrdy":"2015-05-29",
"carrier":"Some Carrier",
"totord":"21703",
"shipped":"4341",
"notes":"These are notes",
"siteid":"Some Site",
"orderstatus":"RDY"},
{"ordnbr":"23456",
"custid":"Anoter Customer",
"custname":"Another Customers Name",
"custordnbr":"65432",
"slsperid":"ID2",
"orddate":"2015-05-19",
"shipdate":"2015-06-05",
"dtrdy":"2015-06-05",
"carrier":"Another Carrier",
"totord":"98875",
"shipped":"0",
"notes":" ",
"siteid":"Another Site",
"orderstatus":"GR"},
etc... The list goes on as there are numerous records.
Second array looks kind of like this(var_dump) I realize this is an array of objects but am casting each line to array.
array(41) {
[0]=>
object(stdClass)#2923 (15) {
["trknbr"]=>
string(12) "7890"
["siteid"]=>
string(3) "This Site"
["flatrate"]=>
string(1) "0"
["ratemile"]=>
string(1) "0"
["miles"]=>
string(3) "822"
["covered"]=>
string(1) "N"
["dateship"]=>
string(10) "0000-00-00"
["trkco"]=>
string(0) ""
["totalchrg"]=>
string(1) "0"
["fuelchrg"]=>
string(1) "0"
["tarp"]=>
string(1) "N"
["shipdirection"]=>
string(3) "out"
["comments"]=>
NULL
["custname"]=>
string(30) "CustName"
["detail"]=>
array(1) {
[0]=>
object(stdClass)#2922 (7) {
["trknbr"]=>
string(12) "BR549"
["ordnbr"]=>
string(6) "12345"
["dtrelease"]=>
string(10) "2015-06-04"
["custid"]=>
string(6) "Custid"
["shipto"]=>
string(13) "Some City"
["slsperid"]=>
string(2) "WE"
["comments"]=>
string(21) "Truck # 2 of 5
$2360"
}
}
}
[1]=>
object(stdClass)#2916 (15) {
["trknbr"]=>
string(12) "34563"
["siteid"]=>
string(3) "My Other Site"
["flatrate"]=>
string(1) "0"
["ratemile"]=>
string(1) "0"
["miles"]=>
string(3) "244"
["covered"]=>
string(1) "N"
["dateship"]=>
string(10) "0000-00-00"
["trkco"]=>
string(0) ""
["totalchrg"]=>
string(1) "0"
["fuelchrg"]=>
string(1) "0"
["tarp"]=>
string(1) "N"
["shipdirection"]=>
string(3) "out"
["comments"]=>
NULL
["custname"]=>
string(25) "Another Customer"
["detail"]=>
array(1) {
[0]=>
object(stdClass)#2830 (7) {
["trknbr"]=>
string(12) "34563"
["ordnbr"]=>
string(6) "34578"
["dtrelease"]=>
string(10) "2015-06-08"
["custid"]=>
string(6) "wwweee"
["shipto"]=>
string(12) "Another City"
["slsperid"]=>
string(3) "RRR"
["comments"]=>
string(31) "DO NOT SHIP BEFORE 6/8
$ 769P"
}
}
}
So what I need to do is, for example, if the ordnbr field is the same for any 2 arrays, I need to append a couple fields from the 2nd array onto the first array. Right now, I am just trying to get the data to return so I can make the comparison and it doesn't seem to be comparing. I have tried using a foreach loop and if array1->ordnbr == array2->ordnbr, then do something... That doesn't work. Tried using in_array and searching for array1->ordnbr in array2.
Nothing I have done works. Can someone please tell me in what direction I should proceed to make these comparisons?
Thanks in advance.
I may not have been real clear on what I need to do... Ok... With Array 1(which did start out as a JSON object but which I converted to multidimensional array using json_decode), I need all rows regardless of whether they match Array 2 or not. However, if ordnbr matches an ordnbr on a row in Array2, then I need to include some data from that row in Array2 into the corresponding row of Array1.
What you would do is to create 2 associative arrays, one for each array with key is ordnbr and value is the whole object contain ordnbr. For example:
$arr1 = array()
foreach ($input1["data"] as $row){
$arr1[$row["ordnbr"]] = $row;
}
The do the same for your second array $arr2. After that, a simple foreach would do the job
foreach ($arr1 as $order_number => $row){
if in_array($order_number, $arr2){
// $row2 will have the same $order_number as $row1
$row2 = $arr2[$order_number];
// then do whatever you need here
// ...
}
}
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.
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.
How to get the last array value of this var_dump?
I do a var_dump on a variable ($submission) and get this:
object(stdClass)#148 (8) {
["sid"]=> string(3) "199"
["nid"]=> string(4) "3042"
["submitted"]=> string(10) "1386113448"
["remote_addr"]=> string(9) "127.0.0.1"
["uid"]=> string(2) "21"
["name"]=> string(8) "SClosson"
["is_draft"]=> string(1) "0"
["data"]=> array(1) {
[1]=> array(1) {
[0]=> string(8) "blahblah"
}
}
}
So I need to store blahblah in a variable from the above array, but how?
Thought I could just get it by doing this: $submission['data'][1][0], but that doesn't work. How do I return blahblah from this?
If you need an array, you can type cast it
$result = (array) $submission;
Or as an object, access the data as public properties
echo $submission->data[1][0];
You can use array_pop if you want to get the last value of an array.
http://www.php.net/manual/en/function.array-pop.php
I have some JSON that I am trying to decode -- it is correctly extracting the value, but also generating an error.
Here is the var_dump:
["success"]=>
bool(true)
["providers"]=>
array(2) {
[0]=>
object(stdClass)#5 (15) {
["address1"]=>
string(14) "3240 W Lake St"
["address2"]=>
NULL
["city"]=>
string(11) "Minneapolis"
["crossStreet"]=>
string(26) "Lake Street & Market Plaza"
["description"]=>
string(55) "test location28402 description of services/prices/hours"
["distance"]=>
float(0.42900015862223)
["lat"]=>
float(44.948469)
["lon"]=>
float(-93.321155)
["name"]=>
string(17) "testlocation28402"
["phone"]=>
string(10) "6125551212"
["precise"]=>
bool(true)
["state"]=>
string(2) "MN"
["url"]=>
string(41) "http://www.testlocation28402.com?id=28402"
["urlCaption"]=>
string(25) "www.testlocation28402.com"
["zip"]=>
string(9) "554164512"
}
[1]=>
object(stdClass)#6 (15) {
["address1"]=>
string(19) "4335 Excelsior Blvd"
["address2"]=>
NULL
["city"]=>
string(16) "Saint Louis Park"
["crossStreet"]=>
NULL
["description"]=>
string(55) "test location26358 description of services/prices/hours"
["distance"]=>
float(0.91979730006713)
["lat"]=>
float(44.935773)
["lon"]=>
float(-93.33489)
["name"]=>
string(17) "testlocation26358"
["phone"]=>
string(10) "6125551212"
["precise"]=>
bool(true)
["state"]=>
string(2) "MN"
["url"]=>
string(41) "http://www.testlocation26358.com?id=26358"
["urlCaption"]=>
string(25) "www.testlocation26358.com"
["zip"]=>
string(9) "554164811"
}
}
["errors"]=>array(0) {
}
}
Above is the var_dump of the variable $json. I am trying to extract the CITY field with:
$json = json_decode($surescript);
foreach ($json as $providers){
foreach($providers as $onespot) {
echo "*";
echo $onespot->city;
echo "\n";
}
}
This outputs:
Warning: Invalid argument supplied for foreach() in /home/content/96/7973196/html/channels/MIL432/storeFinder_2.php on line 153
*Minneapolis
*Saint Louis Park
So, it is getting the correct nested variable, but also throwing off an error on the second foreach loop.
What am I doing incorrectly?
Thanks in advance for your help.
You're iterating over everything in the JSON in your outer loop, meaning that it's trying to parse the success section, the providers section, as well as the errors section.
When you try to parse the success, you can't iterate over the contents in the inner loop, hence the error. The errors section is an array, so you can iterate over it - since there's nothing in it, no error/warning for trying to access city, which wouldn't exist in it.
To only parse the providers:
$json = json_decode($surescript);
foreach ($json->providers as $provider){
echo "*";
echo $provider->city;
echo "\n";
}