I'm developing a plugin that sends WooCommerce order data to a REST API, using a Basic Authentication Header.
As for the WooCommerce order lines, the API documentation tells me to add every order line as an object to the 'lines' array. I'm struggling to set that up.
See the following code for more clarification:
$items = array();
foreach ( $order->get_items() as $item_id => $item_data ) {
$product = $item_data->get_product();
$product_name = $product->get_name();
$item_quantity = $item_data->get_quantity();
$item_total = $item_data->get_total();
$items[] = array(
'unit' => $product_name,
'quantity' => $item_quantity,
'price' => $item_total
);
}
$response = wp_remote_post( $url, array(
'method' => 'POST',
'timeout' => 20,
'headers' => array(
'username' => '***',
'password' => '***',
'company' => '***'
),
'body' => array(
'employee' => 1,
'debtor' => 1,
'deliveryMethod' => 1,
'deliveryAddress' => array(
'address' => $order->get_billing_address_1(),
'postcode' => $order->get_billing_postcode(),
'city' => $order->get_billing_city(),
'country' => 'NL'
),
'lines' => array(
'unit' => $items['unit'],
'quantity' => $items['quantity'],
'price' => $items['price']
)
)
) );
The WordPress debug log tells me it can't find the index of 'unit', 'quantity' and 'price'.
So your array variable would look similar to the following (basing from your example code):
// print_r($items)
Array(
[0] => ['unit' => '', 'quantity' => '', 'price' = ''],
[1] => ['unit' => '', 'quantity' => '', 'price' = ''],
[2] => ['unit' => '', 'quantity' => '', 'price' = ''],
// etc...
)
The empty strings would just have your data.
You're adding an array to an array, so if you wanted to parse through the $items array you could use foreach:
foreach($items as $item) {
print_r($item);
}
That output should be similar to:
Array
(
[unit] => '',
[quantity] => '',
[price] => ''
)
But it would loop over each array in $items, so in my case using the above code it would print_r() three times.
Another way to visualize it is:
print $items[0]['unit'];
print $items[1]['unit'];
print $items[2]['unit'];
Each array is indexed (unless you define a key) so [0] would be the first array in the $items array, then you're referencing the ['unit'] key.
Here's a link to something that could help you understand more: https://www.geeksforgeeks.org/multidimensional-arrays-in-php/
Hope this helps!
Your array apparently looks ok except few things that is different than the documents.
First use 'line_items' instead of 'lines'.
Now, each order may have one or many products so you have to associate 'line_items' with products. And you're trying to get attributes which are related to those product. You got error because you've not associated quantity and price with product_id according to the docs.
'line_items' => [
[
'product_id' => 123,
'quantity' => 2,
'price' => 100
]
]
Unit is something different. Unit could be get from meta. I guess you're referring unit of dimensions. To get meta you can use it like
'line_items' => [
[
'product_id' => 123,
'quantity' => 2,
'price' => 100,
'meta' => [
"key" => "dimension_unit",
"label" => "Dimension Unit",
"value" => "in"
]
]
]
Here I've used every sample data. You can assign your desire data your way.
Hope this help you and your API should work correctly now!
Related
Hi there i need some help to loop an array of items.
The part that I have repeated needs to be looped in order to get multiple items from the database. At this stage I am only to invoice one item where as users generally purchase a few so i need to run a foreach statement I think. Please excuse my ignorance and lack of understanding, I have tried a series of things but they do not seem to work
$json1 = array(
'Date' => $currentDate->format('Y-m-d\TH:i:s'),
'Customer' => array(
'DisplayID' => $phone
),
'CustomerPurchaseOrderNumber' => $ordID,
'Freight' => '0',
'BalanceDueAmount' => '0.0',
'Status' => 'Closed',
'Lines' => /*$orderDetails,*/ array(
array(
'ShipQuantity' => $ShowDetails['quantity'],
'UnitPrice' => $ShowDetails['unit_price'],
'Total' => $ShowDetails['total_price'],
'Item' => array(
'UID' => $productUID,//itemuid(609400gmkit)
),
'Description' => $productTitle. ' ' .$sizeTitle. ' '
.$colorTitle,
'TaxCode' => array(
'UID' => '7d1f2e99-ffe0-4463-9c29-
61d078b392d3'//taxcodeuid(GST)
)
)
),
'Freight' => $shippingprice,//if dg then $10 otherwise $0 unless below
$100
'ShippingMethod' => $ShippingMethod,// if dg the 'MyFreight' otherwise
'transdirect'
);
The portion that i need to loop is as follows :
array(
'ShipQuantity' => $ShowDetails['quantity'],
'UnitPrice' => $ShowDetails['unit_price'],
'Total' => $ShowDetails['total_price'],
'Item' => array(
'UID' => '27d56af8-d3d6-4f0a-b71b-
4586fffbd63a'//itemuid(609400gmkit)
),
'Description' => $productTitle. ' ' .$sizeTitle. ' '
.$colorTitle,
'TaxCode' => array(
'UID' => '7d1f2e99-ffe0-4463-9c29-
61d078b392d3'//taxcodeuid(GST)
)
)*/
I have part of a JSON feed that I need to segment based on variable existance, but its a nested array and I am not quite sure how to write it down.
Here is the code
$postData += array(
'LineItems' => array(
array(
'ItemName' => $_POST['milestone_1_detail'],
'Description' => 'Minimum Guarantee - Installment 1',
'Quantity' => 1,
'Price' => $_POST['milestone_1_amount'],
'SellComm' => 0,
'BuyComm' => 0,
'Accept' => true
),
array(
'ItemName' => $_POST['milestone_2_detail'],
'Description' => 'Minimum Guarantee - Installment 2',
'Quantity' => 1,
'Price' => $_POST['milestone_2_amount'],
'SellComm' => 0,
'BuyComm' => 0,
'Accept' => true
),
array(
'ItemName' => $_POST['milestone_3_detail'],
'Description' => 'Minimum Guarantee - Installment 3',
'Quantity' => 1,
'Price' => $_POST['milestone_3_amount'],
'SellComm' => 0,
'BuyComm' => 0,
'Accept' => true
)
)
);
As you can see, its three (potentially) items all listed in a parent array
I need to do a basic
if ($_POST['milestone_1_amount']) { LineItem1 }
if ($_POST['milestone_2_amount']) { LineItem2 }
if ($_POST['milestone_3_amount']) { LineItem3 }
type condition for all three items,that will still keep those child arrays in the parent array but ONLY show the lineItems that have a value set, but not quite sure how to correctly write the code and retain the array format
Thank you in advance for helping me to stop tearing my hair out
I have problem with my code here, I want convert serialize data in wordpress like this
$data ='a:2:{i:0;a:8:{s:8:"order_id";s:2:"19";s:5:"print";s:18:"type-canvas-framed";s:4:"size";s:12:"08-x-10-inch";s:18:"frame_canvas_color";s:10:"blackframe";s:11:"orientation";s:8:"portrait";s:3:"qty";s:1:"1";s:5:"price";d:42.990000000000002;s:8:"shipping";d:13.800000000000001;}i:1;a:7:{s:8:"order_id";s:2:"19";s:5:"print";s:11:"type-poster";s:4:"size";s:12:"36-x-48-inch";s:11:"orientation";s:8:"portrait";s:3:"qty";s:1:"1";s:5:"price";d:42.990000000000002;s:8:"shipping";d:14.800000000000001;}}' ;
I do parse the data using unseriliaze using unserialize the result like this
$result=array (
0 =>
array (
'order_id' => '19',
'print' => 'type-canvas-framed',
'size' => '08-x-10-inch',
'frame_canvas_color' => 'blackframe',
'orientation' => 'portrait',
'qty' => '1',
'price' => 42.99,
'shipping' => 13.8,
),
1 =>
array (
'order_id' => '19',
'print' => 'type-poster',
'size' => '36-x-48-inch',
'orientation' => 'portrait',
'qty' => '1',
'price' => 42.99,
'shipping' => 14.8,
),
);
I want to looping the array, how to do that in wordpress.
Thanks
you dont need wordpress specific functions for that use:
foreach($result as $key => $value){
// process array
}
just use foreach
foreach($result as $key => $value ) {
echo $value['order_id'];
}
I am trying to add more than one product having same ID but different sizes with Moltin cart. Problem here is, if I am trying to add the same product with different sizes into the Cart, it just increments the quantity instead of appending it. I googled for a solution but I found this happens because of passing the same ID into the Cart::insert() method.
Cart insert Method is:
Cart::insert(array(
'id' => $product->id,
'name' => $product->title,
'price' => $product->price,
'dimension'=>null,
'unit'=>$product->unit,
'quantity' => $quantity,
'image' => $product->image,
'tax' =>$product->taxvalue,
'taxtype'=>$product->tax,
'pincode' =>$pincode,
'shippingfee'=>Session::get('shippingfee'),
'retailerId' =>$retailerIdfromProductId
));
I want to append a new product if the dimension is not null. How do I do this?
I've never used the Moltin cart package, but looking at the code it looks like it builds the item identifier using a combination of the id field and an options array field. Therefore, if the id is the same, but the options are different, it should insert two different items in your cart.
Can you do something like this:
// first item with no dimension
Cart::insert(array(
'id' => $product->id,
'name' => $product->title,
'price' => $product->price,
'unit' => $product->unit,
'quantity' => $quantity,
'image' => $product->image,
'tax' => $product->taxvalue,
'taxtype' => $product->tax,
'pincode' => $pincode,
'shippingfee' => Session::get('shippingfee'),
'retailerId' => $retailerIdfromProductId,
'options' => array(
'dimension' => null
)
));
// second item with 'M' dimension
Cart::insert(array(
'id' => $product->id,
'name' => $product->title,
'price' => $product->price,
'unit' => $product->unit,
'quantity' => $quantity,
'image' => $product->image,
'tax' => $product->taxvalue,
'taxtype' => $product->tax,
'pincode' => $pincode,
'shippingfee' => Session::get('shippingfee'),
'retailerId' => $retailerIdfromProductId,
'options' => array(
'dimension' => 'M'
)
));
I have an array:
$initialarray = array(
0 = array(
'unit' => 1,
'class' => 1,
'value' => 'string1'
),
1 = array(
'unit' => 1,
'class' => 2,
'value' => 'string2'
),
2 = array(
'unit' => 1,
'class' => 2,
'value' => 'string3'
),
3 = array(
'unit' => 2,
'class' => 1,
'value' => 'string4'
)
4 = array(
'unit' => 2,
'class' => 2,
'value' => 'string5'
)
);
What would be the best way to structure it (to group the resulting sub-arrays) depending first on the 'unit' field's values, and then depending on the 'class' field's values, like so:
$resultarray = array(
// array of all the sub-arrays of 'unit' = 1
$unit[1] = array(
// array of all the sub-arrays of 'unit' = 1 and 'class' = 1
$class[1] = array(
0 = array(
'unit' => 1,
'class' => 1,
'value' => 'string1'
)
)
// array of all the sub-arrays of 'unit' = 1 and 'class' = 2
$class[2] = array(
0 = array(
'unit' => 1,
'class' => 2,
'value' => 'string2'
),
1 = array(
'unit' => 1,
'class' => 2,
'value' => 'string3'
)
)
)
// array of all the sub-arrays of 'unit' = 2
$unit[2] = array(
// array of all the sub-arrays of 'unit' = 2 and 'class' = 1
$class[1] = array(
0 = array(
'unit' => 2,
'class' => 1,
'value' => 'string4'
)
)
// array of all the sub-arrays of 'unit' = 2 and 'class' = 2
$class[2] = array(
0 = array(
'unit' => 2,
'class' => 2,
'value' => 'string5'
)
)
)
)
I have asked a similar question here and got a working answer for only one iteration, i.e. for only structuring the array by one of the fields. But I could not make the same solution work for multiple iterations, i.e. for more than one field.
Also, is there a solution to structure a multidimensional array depending on more than two fields?
I think it's not a way of asking the question. It is very simple , you can do this by playing with arrays,keys and etc.... So first you should try hard for the problem. After If you have any problem in the middle of your tries then you can ask that here. I have solved your problem here is the complete code , but next time please do some work and then only post the problem. Never ask for the code.
foreach ($initialarray as $key1=>$val1)
{
foreach ($val1 as $key2=>$val2)
{
if($key2=='unit')
{
$num=$val2;
if($val2!=$num)
$testarr['unit'.$val2]=array();
}
if($key2=='class')
{
$testarr['unit'.$num]['class'.$val2][]=$val1;
}
}
}
print_r($testarr);
I must offer a better way for you and future researchers...
You only need one loop, and you merely need to nominate the result array's key values before using [] to "push" new data into the deepest subarray.
*there is absolutely no need for any condition statements or a second loop.
Code: (Demo)
$initialarray = [
['unit' => 1, 'class' => 1, 'value' => 'string1'],
['unit' => 1, 'class' => 2, 'value' => 'string2'],
['unit' => 1, 'class' => 2, 'value' => 'string3'],
['unit' => 2, 'class' => 1, 'value' => 'string4'],
['unit' => 2, 'class' => 2, 'value' => 'string5']
];
foreach ($initialarray as $row) {
$result[$row['unit']][$row['class']][] = $row;
}
var_export($result);
Output:
array (
1 =>
array (
1 =>
array (
0 =>
array (
'unit' => 1,
'class' => 1,
'value' => 'string1',
),
),
2 =>
array (
0 =>
array (
'unit' => 1,
'class' => 2,
'value' => 'string2',
),
1 =>
array (
'unit' => 1,
'class' => 2,
'value' => 'string3',
),
),
),
2 =>
array (
1 =>
array (
0 =>
array (
'unit' => 2,
'class' => 1,
'value' => 'string4',
),
),
2 =>
array (
0 =>
array (
'unit' => 2,
'class' => 2,
'value' => 'string5',
),
),
),
)
If I may express myself in the following manner: I only see the front-end of your problem and know nothing about its back-end, e.g. "Where does the data come from?", "How is it collected and stored", etc. so my answer might not be a real help but still I'll give my "tuppence".
If you can store all that data in a relational database (in form of table(s)) it would be much more easier and faster(!) to select the needed data from the database instead of rearranging arrays, which will take some more time in comparison.
Just as an example you might then select (and store it into an array) all items which have unit = '1' and / or all items which have class = '2'. That would make life much more easier IMHO, than having all the data in a multidimensional array and then try to sort it / rearrange it. Especially if you do that based on more than one property.