I want to update two variables in my the Woocommerce cart object. I can see the structure of the arrays in the object with:
echo 'Cart Dump: ' . var_dump($woocommerce->session->cart)
This returns:
array(1) { ["01822dd92bc31f60fdb64f0c3c5eb241"]=> array(9) { ["product_id"]=> int(616) ["variation_id"]=> string(0) "" ["variation"]=> string(0) "" ["quantity"]=> int(1) ["addons"]=> array(2) { [0]=> array(3) { ["name"]=> string(5) "Color" ["value"]=> string(13) "Black / Black" ["price"]=> string(0) "" } [1]=> array(3) { ["name"]=> string(8) "Warranty" ["value"]=> string(13) "12 Month Free" ["price"]=> string(0) "" } } ["line_total"]=> float(689) ["line_tax"]=> float(0) ["line_subtotal"]=> float(689) ["line_subtotal_tax"]=> float(0) } } Cart Dump:
I want to be able to set the variables "value" and "price" inside that object.
My next step has been to try to step into the next array and have tried
echo 'Cart Dump: ' . var_dump($woocommerce->session->cart[1])
but I think I am mixing object references with array ones here and I am getting NULL. I can appreciate that I would be better off creating a function for the object but I am not sure how to best approach that if I cannot even access the variable I want to set.
Many thanks in advance.
There are no objects here, it's just that the array key is the string 01822dd92bc31f60fdb64f0c3c5eb241 and not the integer 1.
So to get / set your value, you would use:
$woocommerce->session->cart["01822dd92bc31f60fdb64f0c3c5eb241"]["addons"][0]["value"]
etc.
Depending on your php version you would probably need a temporary variable to get to the first element of your array if you don't know the key:
$temp = reset($woocommerce->session->cart);
$value = $temp["addons"][0]["value"];
You can try this:
//search the key of the array
$cart = $woocommerce->session->cart;
//update values using the key of the array as key
$woocommerce->session->cart[key($cart)]['value'] = 'your value';
$woocommerce->session->cart[key($cart)]['price'] = 'your price';
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.
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'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 am noticing some strange behavior while looping through some data. I'm sure it's something simple, but I can't seem to be able to find the bug.
I have the following logic:
<?php
print 'dumping data : <BR>';
var_dump($portvlan);
print '<BR>';
print 'looping through data: <BR>';
foreach ($portvlan as $vlandetail){
echo 'Vlanid: '.$vlandetail['VlanId'].'<BR>';
echo 'Name: '.$vlandetail['Name'].'<BR>';
echo 'Mode: '.$vlandetail['Mode'].'<BR>';
}
?>
This is the output that I'm getting:
dumping data :
array(3) { ["VlanId"]=> string(2) "33" ["Name"]=> string(6) "USR_33" ["Mode"]=> string(6) "Access" }
looping through data:
Vlanid: 3
Name: 3
Mode: 3
Vlanid: U
Name: U
Mode: U
Vlanid: A
Name: A
Mode: A
What I was expecting was to see it print a row with 3 cells, with the following values:
33, USR_33, Access.
Can you tell me where I'm going wrong?
Thanks.
EDIT 1
This logic works fine when the $portvlan array has more than one entry.
For example, on another set of data, the var_dump gives this result:
array(6) { [0]=> array(3) { ["VlanId"]=> string(1) "1" ["Name"]=> string(1) "1" ["Mode"]=> string(5) "Trunk" } [1]=> array(3) { ["VlanId"]=> int(2) ["Name"]=> int(2) ["Mode"]=> string(5) "Trunk" } [2]=> array(3) { ["VlanId"]=> int(3) ["Name"]=> int(3) ["Mode"]=> string(5) "Trunk" } [3]=> array(3) { ["VlanId"]=> int(4) ["Name"]=> int(4) ["Mode"]=> string(5) "Trunk" } [4]=> array(3) { ["VlanId"]=> int(5) ["Name"]=> int(5) ["Mode"]=> string(5) "Trunk" } [5]=> array(3) { ["VlanId"]=> string(2) "33" ["Name"]=> string(2) "33" ["Mode"]=> string(5) "Trunk" } }
And the loop logic works fine.
$vlandetail will be populated with a different item from the array on every iteration of the loop. You shouldn't be treating $vlandetail as an array. Just use it directly.
To get the key name of the array entry, you have to change the loop structure to this:
foreach ($portvlan as $key => $vlandetail) {
echo $key . ': ' . $vlandetail . '<br>';
}
How you get your $portvlan?
If you can know is $portvlan is not an array of $vlandetail, you can simply do this,
$portvlan = array($portvlan);
// start loop
Or you can do this before you loop it, to make sure $portvlan is a numerical array formed by $vlandetail
$portvlan = (isset($portvlan[0]))?$portvlan:array($portvlan);
// start loop