Get two data with one loop - php

I get two params from some form in a controller like this:
$productIds = $this->getRequest()->getParam('productId');
$productQtys = $this->getRequest()->getParam('qty');
Result:
[productId] => Array(
[0] => 106
[1] => 107
[2] => 108
[3] => 109
)
[qty] => Array(
[0] => 4
[1] => 3
[2] => 2
[3] => 1
)
Good, now i want to get in each loop a productId and qty
I tested this it works for product but i can't get a qty :
foreach($productIds as $prod) {
//some code...
$product = Mage::getModel('catalog/product')
->setStoreId(Mage::app()->getStore()->getId())
->load($prod);
$cart->addProduct($product->getId(), $qty) // here how i get the $qty of each product, if i put it manually it works, 2 for exemple, it add 2 for all products
}

array_combine($productIds,$productQtys)
Result:
array(
[1639] => 6
[1640] => 4
[1641] => 3
[1646] => 2
)
//Thanks to #Tobias F

If your keys are corresponding then you can extend your foreach to the key=>value construction. Then you can use the key in in the qty array directly. Didn't test it but here it goes:
foreach($productIds as $key => $prod) {
$product = Mage::getModel('catalog/product')
->setStoreId(Mage::app()->getStore()->getId())
->load($prod);
$cart->addProduct($product->getId(), $qty[$key])
}

Related

How to Remove duplicate values from Multidimentional array with single unique value in all array

I have multi-dimentional array like below,
$product = array(
"2e471a22b1b994a7cb3f3a40cee9fba2" => array (
"product" => 6004,
"unique_key" => 3a8a5cb029ee3b92cfc90de23e2329ab,
"product_id" => 51,
"line_total"=>99,
"quantity"=>1,
"data"=> array(
"id"=> 51,
"post"=>array(
"ID"=>51,
"post_title"=>"Prodcut four - control",
),
"price"=>99
)
),
"a7d0f813832ec8a2bf24269ff7145d0c" => array (
"product" => 6004,
"unique_key" => c30d1ca26d30aa3dc3c9aa04f0b585ce,
"product_id" => 51,
"line_total"=>99,
"quantity"=>1,
"data"=> array(
"id"=> 51,
"post"=>array(
"ID"=>51,
"post_title"=>"Prodcut four - control",
),
"price"=>99
)
)
);
Need to remove the duplicate values based on 'product_id' array value and increase the quantity values based on number of products.
Note: The above array have 'unique key' too so any single unique key is needed in array result.
Expected Result should be:
$resultproduct = array(
"2e471a22b1b994a7cb3f3a40cee9fba2" => array (
"product" => 6004,
"unique_key" => 3a8a5cb029ee3b92cfc90de23e2329ab,
"product_id" => 51,
"line_total"=>99,
"quantity"=>2,
"data"=> array(
"id"=> 51,
"post"=>array(
"ID"=>51,
"post_title"=>"Prodcut four - control",
),
"price"=>99
)
));
Working code at eval.in
I try and make the code easy to understand so more variables and lines of code than is absolutely required.
Explanation:
1) Need to use the one of original product array index as the output table key e.g. "2e471a22b1b994a7cb3f3a40cee9fba2" for product 51.
2) It needs to be fast relating input productId to the output key. So, I used a lookup table ProductIdList that matches productId to output key.
It is then a two stage lookup to find the entry in the output and add quantities to it.
The code:
// create a product_id => first key table
$productIdList = array();
// output...
$productTotal = array();
foreach ($product as $origIndex => $entry) {
$curProductId = $entry['product_id'];
// check product_id exists in the lookup...
if (isset($productIdList[$curProductId])) { // add to the total...
$productTotalIndex = $productIdList[$curProductId];
$productTotal[$productTotalIndex]['quantity'] += $entry['quantity'];
}
else { // add the entry to the output and the productIdList...
$productIdList[$curProductId] = $origIndex;
$productTotal[$origIndex] = $entry;
}
}
Output: The totals array:
Array
(
[2e471a22b1b994a7cb3f3a40cee9fba2] => Array
(
[product] => 6004
[unique_key] => 3a8a5cb029ee3b92cfc90de23e2329ab
[product_id] => 51
[line_total] => 99
[quantity] => 2
[data] => Array
(
[id] => 51
[post] => Array
(
[ID] => 51
[post_title] => Prodcut four - control
)
[price] => 99
)
)
[test02] => Array
(
[product] => 6664
[unique_key] => c30d1ca26d30aa3dc3c9aa04f0b585ce
[product_id] => 666
[line_total] => 99
[quantity] => 579
[data] => Array
(
[id] => 666
[post] => Array
(
[ID] => 666
[post_title] => Prodcut 666 - control
)
[price] => 99
)
)
)
The productId to original key list:
array (size=2)
51 => string '2e471a22b1b994a7cb3f3a40cee9fba2' (length=32)
666 => string 'test02' (length=6)
You need to loop over each product and use the product_id as the key for a new array. This adds the quantities as it goes, so should work for any quantities other than 1.
$result = [];
foreach ($product as $p)
{
if (isset($result[$p['product_id']]))
{
$result[$p['product_id']]['quantity']+= $p['quantity'];
}
else
{
$result[$p['product_id']] = $p;
}
}
print_r($result);

Get all children items from flat array with nested data structure

I have a flat array of categories. All categories have ID, Parent_id and Name.
The root categories have Parent_id equal to null. They have subcategories that might have them as their parents and their might be subsubcategories that have subcategories as parents. (their might be a lot of levels).
I can get all categories with a single query into a flat array. What I need is - If I take a category (or a subcaegory), how can I get a list of all nested categories (subcategories, subsubcategories) that are included in this category? Got stack with that problem :(
Array looks like this:
Array
(
[0] => Array
(
[pk_i_id] => 2
[fk_i_parent_id] =>
[i_expiration_days] => 30
[i_position] => 0
[b_enabled] => 1
[b_price_enabled] => 1
[s_icon] =>
)
[1] => Array
(
[pk_i_id] => 4
[fk_i_parent_id] =>
[i_expiration_days] => 30
[i_position] => 6
[b_enabled] => 1
[b_price_enabled] => 1
[s_icon] =>
)
[2] => Array
(
[pk_i_id] => 12
[fk_i_parent_id] =>
[i_expiration_days] => 60
[i_position] => 11
[b_enabled] => 1
[b_price_enabled] => 1
[s_icon] =>
)
[3] => Array
(
[pk_i_id] => 13
[fk_i_parent_id] => 108
[i_expiration_days] => 30
[i_position] => 0
[b_enabled] => 1
[b_price_enabled] => 1
[s_icon] =>
)
You can use recursion. It will be looks like this:
function outTree(array $tree, $parentId = null) {
echo '<ul>';
foreach ($tree as $row) {
if ($row['fk_i_parent_id'] == $parent_id) {
echo '<li>' . $row['pk_i_id'];
echo outTree($tree, $row['pk_i_id']);
echo '</li>';
}
}
echo '</ul>';
}

How to parse JSON Array with different keys on the same level

I have Array and i need to get summ of quantity * price. But the array keys on the third level is different.
I use this PHP code but i only can take price & quantity for first item ['506-p1-8_p2-_p3-']
$quantity = $elements['1af7e792-bcff-4a6c-9bdb-dd5023b0251a']['items']['506-p1-8_p2-_p3-'][quantity];
$price = $elements['1af7e792-bcff-4a6c-9bdb-dd5023b0251a']['items']['506-p1-8_p2-_p3-'][price];
$summ = $price*$quantity;
How to parse all levels to get Summ = (price * quantity)
Thank to all who can help me
Array
(
[1af7e792-bcff-4a6c-9bdb-dd5023b0251a] => Array
(
[is_advance] => 1
[items] => Array
(
[506-p1-8_p2-_p3-] => Array
(
[hash] => 506-p1-8_p2-_p3-
[sku] => 501
[itemId] => 506
[quantity] => 6
[price] => 80.75
[currency] => UAH
[priceDesc] =>
[priceParams] => Array
(
[u0420u0430u0437u043cu0435u0440] => 8
)
[name] => qwerty
)
[498-p1-6_p2-_p3-] => Array
(
[hash] => 498-p1-6_p2-_p3-
[sku] => 498
[itemId] => 498
[quantity] => 5
[price] => 500
[currency] => UAH
[priceDesc] =>
[priceParams] => Array
(
[u0420u0430u0437u043cu0435u0440] => 6
)
[name] => qwerty
)
)
)
)
It's hard to tell how the array is generated in the first place. So just going off of the code you've posted, this should sum up the total for every item contained in the array.
$items = $elements['1af7e792-bcff-4a6c-9bdb-dd5023b0251a']['items'];
$sum = 0;
foreach($items as $item) {
$sum += $item['quantity'] * $item['price'];
}
In the sense of flexibility, you want your code as portable as possible. I assume your id isn't always going to be 1af7e792-bcff-4a6c-9bdb-dd5023b0251a, so you'll want to loop through the data that is returned.I don't know how you get the data, that's up to you.
So something like this, should gather the data you require and create an array:
$d = array();
foreach ($data as $id => $item) {
foreach ($item as $key => $values) {
$d[$id][$key]['sum'] = $values['price'] * $values['quantity'];
}
}
print_r($d);
Note: The above code is untested

Loop logic help needed - Can't compare correctly

I have the following table:
And I use this function to get data from it:
function get_cart_by($player_id)
{
global $db;
$sql = 'SELECT DISTINCT(item_id) FROM ' . PCP_MARKET_CART . '
WHERE player_id = ' . (int) $player_id;
$result = $db->sql_query($sql);
$rowset = $db->sql_fetchrowseT($result);
$db->sql_freeresult($result);
$cart = array();
foreach ($rowset as $item)
{
$cart[] = $item['item_id'];
}
return $cart;
}
The result looks like this:
Array
(
[0] => 16
[1] => 17
[2] => 49
[3] => 48
[4] => 18
[5] => 19
[6] => 51
)
Now I have an array that lists all my products from another table without looking at the player_id. I want to use the array demonstrated above and add a custom class to the items that do not use the player_id, like show which items the user already has on cart.
The other array that lists all the products looks like this:
Array
(
[0] => Array
(
[item_id] => 16
[parent_id] => 11
[cat_position] => 0
[item_position] => 1
[item_type] => product
[item_title] => Custom Business
[item_description] => Some description
[item_price] => 9.99
[item_units] => 500
[item_preview] => http://i.imgur.com/3eCpMMm.png
[times_sold] => 0
[daopay_url] => http://i.imgur.com/QA7bBfJ.jpg
[public] => 1
[time] => 1384709635
)
[1] => Array
(
[item_id] => 17
[parent_id] => 11
[cat_position] => 0
[item_position] => 1
[item_type] => product
[item_title] => Custom Business
[item_description] => Some description
[item_price] => 9.99
[item_units] => 500
[item_preview] => http://i.imgur.com/3eCpMMm.png
[times_sold] => 0
[daopay_url] => http://i.imgur.com/QA7bBfJ.jpg
[public] => 1
[time] => 1384709635
)
[2] => Array
(
[item_id] => 49
[parent_id] => 11
[cat_position] => 0
[item_position] => 1
[item_type] => product
[item_title] => Custom Business
[item_description] => Some description
[item_price] => 9.99
[item_units] => 500
[item_preview] => http://i.imgur.com/3eCpMMm.png
[times_sold] => 0
[daopay_url] => http://i.imgur.com/QA7bBfJ.jpg
[public] => 1
[time] => 1384709635
)
)
Now based on the first array, I want to mark the same item IDs on the second arrays and show that they are different (on cart).
I have tried quite a lot and for some reason, I managed to mark only item_id 16 and 17, the rest are not getting "marked" for some reason.
This is the code I used:
$cartar = $market->get_cart_by($user->data['player_id']);
$cartln = sizeof($cartar) - 1;
// Fetch items of the selected category
$items = $market->fetch_cat_items($cat_id); // Equivalent to the array above
$index = 0;
print_r($items);
foreach ($items as $item)
{
$name = $item['item_name'];
if ($cartln >= $index)
{
if ($cartar[$index] == $item['item_id'])
$name .= $cartar[$index];
}
echo $name;
$index++;
}
I tried to make the example explain my case the best way possible. So, when I echo out $name it only outputs thename16 and thename17 (those two), but it doesn't continue to 49 and so on.
Please be aware that the array with all the products in it is quite large, I made it shorter for demonstration purposes only.
Were am I failing in my code? Why are only the first two items getting "marked"? I'm quite in a hurry right now, once I get back from a meeting I'll try to explain my issue further.
i don't know if i understood correctly but maybe you want to do it like this:
foreach ($items as $item) {
$name = $item['item_name'];
if(in_array($item['item_id'],$cartar)) {
$name .= $item['item_id'];
}
echo $name;
}
used in_array() to check if the item_id exists somewhere in $cartar. No matter on which position in array.

Unserialize from MySQL into a Multi-dimensional PHP array

I have a PHP/MySQL e-commerce site that is placing order detail information into a serialized array alongside customer address info.
I want to be able to pull out the order items field, unserialize it and then combine the order items into one master array of ALL ordered items that can be manipulated in order to count how many orders of a specific product have been made.
The arrays look like this when I print_r the unserialized rows. Below are two order arrays, one with 3 products, and the second with only one.
The array values are ID #, SKU #, Quantity, Product Name, Price.
I want to be able to combine ALL orders into one array and then sum the total quantities for each unique ID or SKU number.
I realize this type of thing is drop dead simple if the data was clean in MySQL, but such is life. Any thoughts on how to manipulate these arrays would be truly appreciated.
In this case want to end up with 4 arrays, with the 629/01-3600 ones being combined such that the quantity value is now 2
Many thanks.
Array
(
[0] => Array
(
[1] => 488
[5] => 23-1000
[2] => 3
[3] => PRODUCT NAME
[4] => 2.50
)
[1] => Array
(
[1] => 423
[5] => 24-2300
[2] => 1
[3] => PRODUCT NAME
[4] => 3.50
)
[2] => Array
(
[1] => 506
[5] => 23-2800
[2] => 1
[3] => PRODUCT NAME
[4] => 2.50
)
[3] => Array
(
[1] => 629
[5] => 01-3600
[2] => 1
[3] => PRODUCT NAME
[4] => 7.50
)
)
Array
(
[0] => Array
(
[1] => 629
[5] => 01-3600
[2] => 1
[3] => PRODUCT NAME
[4] => 7.50
)
)
EDIT:
I wanted to add what eventually did what I was looking for
foreach($query->result as $row)
{
$items[] = unserialize( $row['FIELDNAME'] );
}
foreach($items as $item)
{
foreach($item as $order)
{
if( isset($output_array[$order[1]]) )
{
$output_array[$order[1]]['quantity'] += $order[2];
}
else
{
$output_array[$order[1]] = array (
'name' => $order[3],
'quantity' => $order[2],
'sku' => $order[5]
);
}
}
}
I then used this sorting function to sort on the quantity: http://www.php.net/manual/en/function.sort.php#99419
This is a little bit of code so I've separated it into chunks.
This is my recreation of your two arrays. The last line puts them into one.
$items = array(
array(
1 => 488,
5 => '23-1000',
2 => 3,
3 => 'PRODUCT NAME',
4 => 2.50
),
array(
1 => 423,
5 => '24-2300',
2 => 1,
3 => 'PRODUCT NAME',
4 => 3.50
),
array(
1 => 506,
5 => '23-2800',
2 => 1,
3 => 'PRODUCT NAME',
4 => 2.50
),
array(
1 => 629,
5 => '01-3600',
2 => 1,
3 => 'PRODUCT NAME',
4 => 7.50
)
);
$array_2 = array(
array(
1 => 629,
5 => '01-3600',
2 => 1,
3 => 'PRODUCT NAME',
4 => 7.50
)
);
// Put the two arrays together (master array)
$new_array = array_merge($items, $array_2);
Next, we create two arrays to that will use the SKU# and another for the IDs.
// What the items will be sorted by
$skus = array();
$ids = array();
The more complicated part
// Loop through the combined items
foreach( $new_array as $item ) {
/**
* Check if the item's SKU number
* has been added to the $skus array.
*
* If it has then add the old qty with the current item's
*
* Else, the item hasn't been added yet,
* then add the entire item to the list
*/
if( isset($skus[$item[5]]) ) {
// If it exists, then add the new qty
$skus[$item[5]][2] += $item[2];
}else {
// If it doesn't exist, then append it to the array
$skus[$item[5]] = $item;
}
// Do the same thing as above
// except for the id numbers
if( isset($ids[$item[1]]) ) {
// If it exists, then add the new qty
$ids[$item[1]][2] += $item[2];
}else {
// If it doesn't exist, then append it to the array
$ids[$item[1]] = $item;
}
}
Make sure everything is the way you want it
echo '<h2>SKU Numbers</h2>';
echo '<pre>';
print_r($skus);
echo '</pre>';
echo '<h2>ID Numbers</h2>';
echo '<pre>';
print_r($ids);
echo '</pre>';
Hope this helps.
EDIT
For this code to work during the actual loop, you can try something like this. While I'm not completely sure if this will work out of the box, it should be a good place to start.
// What the items will be sorted by
$skus = array();
$ids = array();
foreach( $result as $row ) {
$row = unserialize($row);
/**
* MODIFIED
*
* Check if the $row's SKU number
* has been added to the $skus array.
*
* If it has then add the old qty with the current $row's qty
*
* Else, the $row hasn't been added yet,
* then add the entire $row to the list
*/
if( isset($skus[$row[5]]) ) {
// If it exists, then add the new qty
$skus[$row[5]][2] += $row[2];
}else {
// If it doesn't exist, then append it to the array
$skus[$row[5]] = $row;
}
// Do the same thing as above
// except for the id numbers
if( isset($ids[$row[1]]) ) {
// If it exists, then add the new qty
$ids[$row[1]][2] += $row[2];
}else {
// If it doesn't exist, then append it to the array
$ids[$row[1]] = $row;
}
}

Categories