catalogProductUpdate multiple category IDs - php

I'm trying to update the website and category IDs for a number of products in Magento and I'm having issues. Here's my code:
$client = new SoapClient('http://magentohost/api/v2_soap/?wsdl');
$session = $client->login('apiUser', 'apiKey');
$productarray = array("12345" => "1,2,3", "67890" => "1,5,6");
foreach ($productarray as $product_id => $cats) {
$update = array(
'websites' => array(1,2,3),
'categories' => array($cats)
);
$updatewebsite = $client->catalogProductUpdate($session,$product_id,$update);
}
When I run this code, it's changing the products to have the new website IDs but it's only updating the category IDs with the first one in $cats.
For example, "12345" will only have category ID 1 and not 2 or 3 as it should have.
When I print out what $cats is for each product, it's showing me the info correctly (as "1,2,3" and "1,5,6" for the examples above).
I'm not sure what I've done but I just can't seem to get it to update all the category IDs. I've got thousands of products to run through that all have different category IDs so I can't be doing this manually!
EDIT - SOLVED
I've changed my code so it's now like this (which works):
$client = new SoapClient('http://magentohost/api/v2_soap/?wsdl');
$session = $client->login('apiUser', 'apiKey');
$productarray = array("12345" => "1,2,3", "67890" => "1,5,6");
foreach ($productarray as $product_id => $cats) {
$cats = explode(",", $cats);
$update = array(
'websites' => array(1,2,3),
'categories' => $cats
);
$updatewebsite = $client->catalogProductUpdate($session,$product_id,$update);
}

The categories property would expect an array of IDs, whereas you're passing a string. Try using explode() to break it up:
foreach ($productarray as $product_id => $cats) {
$update = array(
'websites' => array(1,2,3),
'categories' => explode(',', $cats)
);
$updatewebsite = $client->catalogProductUpdate($session,$product_id,$update);
}

Related

How to create 2 collections based from an array with 2 count in PHP?

I know this is a basic question and I'm sorry I can't answer, but how can I create 2 collections based from an array with 2 values in Laravel/PHP? Here's my code:
$received_items = ReceiveItems::where('voucher_id', '=', $request->voucher_id)->get();
foreach($received_items as $received_item) {
$product_ids = $received_item->product_id;
foreach($product_ids as $product_item_no => $product_id) {
$products = Product::where('id', '=', $product_id);
$voucher_cost = $products->value('cost');
$qty_addend = $received_item->qty_per_item;
$list = array(
'product_item_no' => $product_item_no + 1,
'product_name' => $products->value('name'),
'size' => $products->value('size'),
'qty_addend' => $qty_addend[$product_item_no],
'voucher_cost' => $voucher_cost,
'ext_cost' => number_format($voucher_cost * $qty_addend[$product_item_no], 2)
);
$list = (object)$list;
$received_item->list = $list;
$data = collect([$list]);
}
}
return $data;
Basically, the $product_ids is the array I want to get and count($product_ids) is returning 2, but it's just creating the collection from the 2nd array value. See screenshot below:
screenshot.png
Any help is much appreciated.
In your $list variable it will only store last product_id data, because you have to take $list as multi-dimensional array.
You have to take $list variable out of the second loop, so it not overwrite data.
Try below code:
$received_items = ReceiveItems::where('voucher_id', '=', $request->voucher_id)->get();
foreach($received_items as $received_item) {
$product_ids = $received_item->product_id;
$list = []; // declare list variable here
foreach($product_ids as $product_item_no => $product_id) {
$products = Product::where('id', '=', $product_id);
$voucher_cost = $products->value('cost');
$qty_addend = $received_item->qty_per_item;
$list[] = array( // make it multi-dimentional array
'product_item_no' => $product_item_no + 1,
'product_name' => $products->value('name'),
'size' => $products->value('size'),
'qty_addend' => $qty_addend[$product_item_no],
'voucher_cost' => $voucher_cost,
'ext_cost' => number_format($voucher_cost * $qty_addend[$product_item_no], 2)
);
}
// take this code out of loop
$list = (object)$list;
$received_item->list = $list;
$data = collect([$list]);
}
return $data;

Magento, php foreach to string

I'm using a Magento extension which sends shipments automatically to my carrier. Now I want the 'custom_id' field to be a comma separated list of the product sku's in the shipment.
First part of the code:
$items = $myParcelShipment->getOrder()->getAllItems();
foreach($items as $item) {
$sku= $item->getSku();
}
$CUSTOMLIST = [HERE A COMMA SEPARATED LIST OF PRODUCT SKU'S]
Second part:
$data = array(
'ToAddress' => array(
'name' => trim($shippingAddress->getName()),
'postcode' => trim($shippingAddress->getPostcode()),
'street' => trim($streetData['streetname']),
'house_number' => trim($streetData['housenumber']),
'town' => $shippingAddress->getCity(),
),
'ProductCode' => $this->_getProductCodeData($myParcelShipment),
'custom_id' => $CUSTOMLIST,
);
Any suggestions on how to transform the foreach loop into a comma separated string to be used as 'custom_id'?
Use following code
$skus = array();
$items = $myParcelShipment->getOrder()->getAllItems();
foreach($items as $item) {
$skus[] = $item->getSku();
}
$CUSTOMLIST = implode(',', $skus);

How to unset / remove item from two dimensional associative array

On sound advice from this Forum, I am re-writing code involving multi-dimensional array SESSIONS cart so that the product ID is the array name (I think I am explaining this correctly). I can add to the array, but I cannot remove anything. I am using an array to add new item data to the SESSIONS array. The code below represents a test adding items to the array and finally trying and failing to delete one. Any assistance in finding my errors is appreciated.
echo '************** STEP ONE **********************';
// Initialize array
$_SESSION['cart'] = array();
// Array of newitem
$id = 181;
$newitem = array(
$id => array(
'quantity' => 1,
'part_number' => '600N5630-501',
)
);
// Add newitem to cart
$_SESSION['cart'][] = $newitem;
// Display cart array with one item
var_dump($_SESSION['cart']);
echo '************** STEP TWO **********************';
// Array of newitem
$id = 33;
$newitem = array(
$id => array (
'quantity' => 1,
'part_number' => '369A7170-11',
)
);
// Add newitem to cart
$_SESSION['cart'][] = $newitem;
// Display cart array with two items
var_dump($_SESSION['cart']);
echo '************** STEP THREE **********************';
// Array of newitem
$id = 34;
$newitem = array(
$id => array (
'quantity' => 1,
'part_number' => '369A7171-15',
)
);
// Add newitem to cart
$_SESSION['cart'][] = $newitem;
// Display cart array with three items
var_dump($_SESSION['cart']);
echo '************** STEP FOUR **********************';
// Unset by ID
$id = 34;
unset($_SESSION['cart'][$id]);
// Display cart array with two items
var_dump($_SESSION['cart']);
When you use $_SESSION['cart'][] it adds a new array item dynamically with the next index. You are then adding another two arrays under that one. Try creating the index with the specific $id:
$id = 181;
$newitem = array(
'quantity' => 1,
'part_number' => '600N5630-501',
);
// Add newitem to cart
$_SESSION['cart'][$id] = $newitem;
Alternately you could add/replace them like this:
$id = 181;
$newitem = array(
$id => array(
'quantity' => 1,
'part_number' => '600N5630-501',
)
);
// Add newitem to cart
$_SESSION['cart'] = array_replace($_SESSION['cart'], $newitem);

php function add foreach array on another array to populate a select drop down

I started this PHP function. This function is to populate a dropdown select menu in WordPress.
The acf/load_field hook helps me easily hook this in. See documentation here. http://www.advancedcustomfields.com/resources/filters/acfload_field/
This is my function which uses get_posts to query my circuit post_type. This bit works fine.
See below...
function my_circuit_field( $field )
{
$circuits = get_posts(array(
"post_type" => "circuit",
"post_status" => "publish",
"orderby" => "menu_order",
"order" => "ASC",
"posts_per_page" => -1
));
$field['choices'] = array();
$field['choices'] = array(
0 => 'Select a circuit...'
);
foreach($circuits as $circuit){
$field['choices'] = array(
$circuit->post_title => $circuit->post_title
);
}
return $field;
}
add_filter('acf/load_field/name=event_calendar_circuit', 'my_circuit_field');
The problem I am having is that...
$field['choices'] = array(
0 => 'Select a circuit...'
);
is not joining onto the front of this...
foreach($circuits as $circuit){
$field['choices'] = array(
$circuit->post_title => $circuit->post_title
);
}
Only the $circuits foreach is showing in my dropdown, I would like 'Select a circuit' to appear as the first option in the dropdown select menu.
Can anyone help me understand where I am going wrong?
When you use =, it replaces the current value with the one after the = sign. You're replacing the whole value of $field['choices'] each time you assign a new value.
You probably want to do something like
foreach($circuits as $circuit){
$field['choices'][$circuit->post_title] = $circuit->post_title;
}
By the way, the line $field['choices'] = array(); is useless in your code, as you change the value in the following line.
Use this:
$field['choices'] = array(
0 => 'Select a circuit...'
);
$arr = array();
foreach($circuits as $circuit){
$arr = array(
$circuit->post_title => $circuit->post_title
);
$field['choices'] = array_merge($field['choices'],$arr);
}
print_r($field);
OUTPUT:
Array
(
[choices] => Array
(
[0] => Select a circuit...
//and other fields
//with the 0 index value
//same as you are requiring
)
)

PHP: How to create a jagged array structure to represent grouped records from a database

This seems like a simple challenge, but I'm struggling.
I want to retrieve records using a join query on two database tables and represent them as an array of arrays, whereby each of the elements in the root array is a parent record and each nested element represents a child record.
The SQL query is working fine, and it returns a set of rows in which the channel_key column is a grouping column.
Here's my attempt at populating the array structure from the rows:
$rows = $db->get_results($query);
$key = '';
$programmes = array();
foreach ($rows as $row) {
$programme = array(
'title' => $row->title,
'start' => $row->start,
'duration' => $row->duration
);
$programmes[] = $programme;
if ($key != $row->channel_key) {
$channels[] = array(
'key' => $row->channel_key,
'programme' => $programmes
);
$key = $row->channel_key;
$programmes = array();
}
}
Unfortunately this only populates the root level arrays (the ones that correspond to the parent records).
Any suggestions please?
Thanks,
Tim
You only have one programme in the $programmes array when you assign it to the channel.
An alternative would be to build the channel array with the channel_key.
e.g.
<?php
$channels = array();
foreach($rows as $row) {
// Create the channel node if it doesn't exist
if (!isset($channels[$row->channel_key])) {
$channels[$row->channel_key] = array(
'key' => $row->channel_key,
'programme' => array()
);
}
$programme = array(
'title' => $row->title,
'start' => $row->start,
'duration' => $row->duration
);
// Add to the existing channel node.
$channels[$row->channel_key]['programme'][] = $programme;
}
Simple solution can be.
$rows = $db->get_results($query);
$key = '';
$programmes = array();
foreach ($rows as $row) {
$programme = array(
'title' => $row->title,
'start' => $row->start,
'duration' => $row->duration
);
$programmes[$row->channel_key][] = $programme;
}

Categories