I have an app where the user is able to choose themes and plugins but they are also able to choose none of the two. So to check all the possible options I need a 4 clause if-statement to check every situation. In the meantime, this if-statement grew exponentially and now it's very large. I used Repository for some bits to refactor the if-statement a bit but its still way too large and uclear. This is the if-statement
public function store(Request $request)
{
$selectedPlugin = null;
$selectedPlugins = array();
$price = null;
foreach($request->input('plugin') as $key => $value) {
if ($value === 'selected') {
$selectedPlugin = $key;
$plugin = Product::find($selectedPlugin);
if($plugin == null)
{
continue;
} elseif ($plugin != null) {
$price += $plugin->price;
echo "ID: " . $plugin->id . "<br>";
$selectedPlugins[$plugin->id] = $plugin->toArray();
$request->session()->put('chosen_plugins.' . 'PluginID' . $plugin->id, $plugin->toArray());
$request->session()->put('chosen_plugins.' . 'PluginID' . $plugin->id .'.composer_package', $plugin->productable->composer_package);
}
}
}
if(session()->exists('chosen_plugins') == true) {
$products = Session::get('chosen_plugins');
if(session()->exists('chosen_theme') == true)
{
$products['theme'] = Session::get('chosen_theme');
$themePrice = Session::get('chosen_theme')['price'];
$subtotal = $price + $themePrice;
$vat = 21/100 * $subtotal;
$priceSum = $subtotal + $vat;
} elseif (session()->exists('chosen_theme') == false) {
$subtotal = $price;
$vat = 21/100 * $subtotal;
$priceSum = $subtotal + $vat;
}
$data = [$subtotal, $vat, $priceSum];
$order = $this->_orderRepository->createOrderIfSessionExist($data, $products);
return redirect()->to('/ordersummary/'. $order->id);
} elseif (session()->exists('chosen_plugins') == false ) {
if(session()->exists('chosen_theme') == true)
{
$theme = Session::get('chosen_theme');
$subtotal = $theme['price'];
$vat = 21/100 * $subtotal;
$priceSum = $subtotal + $vat;
} elseif (session()->exists('chosen_theme') == false) {
$subtotal = 35;
$vat = 21/100 * $subtotal;
$priceSum = $subtotal + $vat;
}
$data = [$subtotal, $vat, $priceSum];
$order = $this->_orderRepository->createOrderIfSessionDoesntExist($data);
if (session()->exists('chosen_theme') == true) {
$orderItems = new Orderitems;
$orderItems->order_id = $order->id;
$orderItems->product_id = $theme['id'];
$orderItems->price = $theme['price'];
$orderItems->save();
return redirect()->to('/ordersummary/'. $order->id);
} elseif (session()->exists('chosen_theme') == false) {
return redirect()->to('/ordersummary/'. $order->id);
}
}
}
I need some help to refactor this if-statement. Thanks in advance!
Related
I have a table with columns
-Deposits
-Withdrawals
-Running Balance
I am using the values inside the first two columns to calculate the Running balance in the Running Balance column.
The issue.
The calculation is working fine - just that it's doing so in reverse. If you look at the "Entry Id" column, I have the entry Ids which I would like to use for the calculation, or whichever way works. If we use the Entry ID column then I need the calculation to happen from the smallest to the largest Entry ID.
Here is my code.
function display_form_entries_shortcode() {
global $wpdb;
$form_id = 73;
$current_user_id = get_current_user_id();
$entries = FrmEntry::getAll(array('form_id' => $form_id, 'user_id' => $current_user_id), ' ORDER BY created_at DESC', '', true, 999999);
if(empty($entries)) {
return 'No entries found for form ID '.$form_id.' for user ID '.$current_user_id;
}
$form_fields = FrmField::get_all_for_form($form_id);
$field_labels = array();
foreach ($form_fields as $field) {
$field_labels[$field->id] = $field->name;
}
$table_name_n = $wpdb->prefix . 'frm_fields';
$table_name = $wpdb->prefix . 'frm_item_metas';
// Add the new columns
$field_labels[787] = "Deposits";
$field_labels[788] = "Withdrawals";
$field_labels[789] = "Running Balance";
$output = '<table>';
$output .= '<tr><th>' . implode('</th><th>', $field_labels) . '</th></tr>';
$running_balance = 0;
global $m_field;
foreach ($entries as $entry) {
$entry_values = array();
foreach ($field_labels as $field_id => $field_label) {
$field_value = '';
if ($field_id == 746) { //return "Select Account" field
$row = $wpdb->get_row( "SELECT * FROM $table_name_n WHERE field_key = 'f2ego'" );
$options = unserialize( $row->options );
$fieldi_value = $options[FrmEntryMeta::get_entry_meta_by_field($entry->id, $field_id)];
}
//Running Balance Calculations
if ($field_id == 787) {
if ($entry->metas[783] == 'Money In' && $fieldi_value == $m_field) {
$field_value = $entry->metas[727] ? $entry->metas[727] : $entry->metas[738];
if ($entry->metas[736]) {
$field_value -= $entry->metas[736];
}
$field_value = $field_value > 0 ? $field_value : 0;
$running_balance += $field_value;
} else {
$field_value = 0;
}
} else if ($field_id == 788 && $fieldi_value == $m_field) {
if ($entry->metas[783] == 'Money Out') {
$field_value = $entry->metas[727] ? -$entry->metas[727] : -$entry->metas[738];
if ($entry->metas[736]) {
$field_value += $entry->metas[736];
}
$field_value = $field_value < 0 ? $field_value : 0;
$running_balance += $field_value;
} else {
$field_value = 0;
}
}
else if ($field_id == 789 && $fieldi_value == $m_field) {
$field_value = $running_balance;
}
else {
$field_value = FrmEntryMeta::get_entry_meta_by_field($entry->id, $field_id);
}
//End of calculations
$entry_values[] = $field_value;
}
if(!in_array($m_field, [$entry_values[1], $entry_values[11], $entry_values[16]])) {
continue;
}
if (!empty($entry_values)) {
$output .= '<tr><td>' . implode('</td><td>', $entry_values) . '</td></tr>';
}
}
$output .= '</table>';
return $output;
}
add_shortcode('display_form_entries', 'display_form_entries_shortcode');
I have run out of options trying to force the calculation in order of the Entry IDs. Any assistance is welcome.
I have table lids with under 430k entries.
How can I do SELECT query faster, optimized because now this query working under 5-7 minutes.
Heard something about Eloquent chunk in Laravel, but need clear PHP solution or with DB object.
Maybe with 'for' construction to process 100-1000 entries at a time, smthng like this.
Tried to do 'for' construction, but don't know how to do this optimized.
Be gentle with me pls :)
Want to know your opinion.
How can i upgrade it?
UPD: Did something like this
$count = $db->doQuery("SELECT count(*) FROM `lids`"); // db - my custom object with Database connection
$count = $count[0]['count(*)'];
$hundreds = $count / 100; // get 'for' counts
$start = 43; // id index starts from 43 in the table
$end = 142;
for ($index = 1; $index < $hundreds; $index++) {
$leads = [];
$leads = $db->doQuery("SELECT * FROM `lids` WHERE `id` BETWEEN " . $start . " AND " . $end . "");
// var_dump($leads);
// die();
if (empty($leads)) {
$start += 100;
$end += 100;
continue;
}
$uniques = [];
foreach ($leads as $lead) {
if (empty($lead['json_vars'])) continue;
$vars = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $lead['json_vars']); // hot fix for charset, from DB comes string in utf8mb4
$json = json_decode($vars, true);
if (!isset($json['ser']['HTTP_COOKIE']) || !str_contains($json['ser']['HTTP_COOKIE'], '_fbc')) continue;
$lead['json_vars'] = $json['ser']['HTTP_COOKIE'];
// check for unique values
if (!isset($uniques[$lead['id']]) || $uniques[$lead['id']]['phone'] != $lead['phone']) {
$uniques[$lead['id']] = $lead;
}
}
foreach ($uniques as $unique) {
$lid = Lid::create($unique);
}
$start += 100;
$end += 100;
// here i get residue of entries
if ($hundreds - $index < 1) {
$leads = $db->doQuery("SELECT * FROM `lids` WHERE `id` IN(" . ($count - $hundreds * 100) . ", " . $count . ") AND WHERE ");
foreach ($leads as $lead) {
$json = json_decode(preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $lead['json_vars']), true);
if (!str_contains($json['ser']['HTTP_COOKIE'], '_fbc')) continue;
$lead['json_vars'] = $json['ser']['HTTP_COOKIE'];
$lid = Lid::create($lead);
}
}
}
Upd2:
$db = new Database();
$counter = 0;
$scriptStart = date('d.m.Y H:i:s', strtotime('now'));
$lastRemote = $db->lastId('lids');
$lastInner = Lid::all(['id'])->last();
$lastInner = $lastInner->id;
$count = $lastRemote - $lastInner;
if ($count < 0) {
echo 'no new objects, canceled';
return false;
}
$start = $lastInner + 1;
$end = $lastRemote;
$fewEntries = false;
if ($count < 500) {
$fewEntries = true;
$index = $lastInner;
$hundreds = $lastRemote;
} else {
$index = 1;
$hundreds = $count / 100;
$end = $start + 99;
}
if ($fewEntries) {
$leads = $db->itemsBetween('lids', 'id', [$start, $end]);
$uniques = [];
foreach ($leads as $lead) {
if (empty($lead['json_vars'])) continue;
$vars = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $lead['json_vars']);
$json = json_decode($vars, true);
if (!isset($json['ser']['HTTP_COOKIE']) || !str_contains($json['ser']['HTTP_COOKIE'], '_fbc')) continue;
$lead['json_vars'] = $json['ser']['HTTP_COOKIE'];
if (
!isset($uniques[$lead['id']]) ||
$uniques[$lead['id']]['phone'] != $lead['phone'] &&
$uniques[$lead['id']]['ip'] != $lead['ip'] &&
$uniques[$lead['id']]['request_link'] != $lead['request_link']
) {
$uniques[$lead['id']] = $lead;
}
}
foreach ($uniques as $unique) {
$lid = Lid::create($unique);
$counter++;
}
} else {
for ($index; $index < $hundreds; $index++) {
$leads = [];
$leads = $db->itemsBetween('lids', 'id', [$start, $end]);
// var_dump($leads);
// die();
$uniques = [];
foreach ($leads as $lead) {
if (empty($lead['json_vars'])) continue;
$vars = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $lead['json_vars']);
$json = json_decode($vars, true);
if (!isset($json['ser']['HTTP_COOKIE']) || !str_contains($json['ser']['HTTP_COOKIE'], '_fbc')) continue;
$lead['json_vars'] = $json['ser']['HTTP_COOKIE'];
if (
!isset($uniques[$lead['id']]) ||
$uniques[$lead['id']]['phone'] != $lead['phone'] &&
$uniques[$lead['id']]['ip'] != $lead['ip'] &&
$uniques[$lead['id']]['request_link'] != $lead['request_link']
) {
$uniques[$lead['id']] = $lead;
}
}
foreach ($uniques as $unique) {
$lid = Lid::create($unique);
$counter++;
}
$start += 100;
$end += 100;
}
}
$scriptEnd = date('d.m.Y H:i:s', strtotime('now'));
echo 'added in table: ' . $counter . PHP_EOL;
echo 'started at: ' . $scriptStart . PHP_EOL;
echo 'ended at: ' . $scriptEnd . PHP_EOL;
Resolved my problem with optimization of my trash code XD
$db = new Database();
$counter = 0;
$scriptStart = date('d.m.Y H:i:s', strtotime('now'));
$lastRemote = $db->lastId('lids');
$lastInner = Lid::all(['id'])->last();
$lastInner = $lastInner->id;
$count = $lastRemote - $lastInner;
if ($count < 0) {
echo 'no new objects, canceled';
return false;
}
$start = $lastInner + 1;
$end = $lastRemote;
$fewEntries = false;
if ($count < 500) {
$fewEntries = true;
$index = $lastInner;
$hundreds = $lastRemote;
} else {
$index = 1;
$hundreds = $count / 100;
$end = $start + 99;
}
if ($fewEntries) {
$leads = $db->itemsBetween('lids', 'id', [$start, $end]);
$uniques = [];
foreach ($leads as $lead) {
if (empty($lead['json_vars'])) continue;
$vars = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $lead['json_vars']);
$json = json_decode($vars, true);
if (!isset($json['ser']['HTTP_COOKIE']) || !str_contains($json['ser']['HTTP_COOKIE'], '_fbc')) continue;
$lead['json_vars'] = $json['ser']['HTTP_COOKIE'];
if (
!isset($uniques[$lead['id']]) ||
$uniques[$lead['id']]['phone'] != $lead['phone'] &&
$uniques[$lead['id']]['ip'] != $lead['ip'] &&
$uniques[$lead['id']]['request_link'] != $lead['request_link']
) {
$uniques[$lead['id']] = $lead;
}
}
foreach ($uniques as $unique) {
$lid = Lid::create($unique);
$counter++;
}
} else {
for ($index; $index < $hundreds; $index++) {
$leads = [];
$leads = $db->itemsBetween('lids', 'id', [$start, $end]);
// var_dump($leads);
// die();
$uniques = [];
foreach ($leads as $lead) {
if (empty($lead['json_vars'])) continue;
$vars = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $lead['json_vars']);
$json = json_decode($vars, true);
if (!isset($json['ser']['HTTP_COOKIE']) || !str_contains($json['ser']['HTTP_COOKIE'], '_fbc')) continue;
$lead['json_vars'] = $json['ser']['HTTP_COOKIE'];
if (
!isset($uniques[$lead['id']]) ||
$uniques[$lead['id']]['phone'] != $lead['phone'] &&
$uniques[$lead['id']]['ip'] != $lead['ip'] &&
$uniques[$lead['id']]['request_link'] != $lead['request_link']
) {
$uniques[$lead['id']] = $lead;
}
}
foreach ($uniques as $unique) {
$lid = Lid::create($unique);
$counter++;
}
$start += 100;
$end += 100;
}
}
$scriptEnd = date('d.m.Y H:i:s', strtotime('now'));
echo 'added in table: ' . $counter . PHP_EOL;
echo 'started at: ' . $scriptStart . PHP_EOL;
echo 'ended at: ' . $scriptEnd . PHP_EOL;
I'm trying to generate auto description from tags.
The code was working but after updating my site to Laravel 6 in stop working. I need to get it back working.
if( !empty( $request->description ) )
{
$description = Helper::checkTextDb($request->description);
}
else
{
$a_key = explode(",", strtolower($request->tags));
if(count($a_key) == 0)
$description = 'This is a great thing';
else
{
$description_get_keys = '';
foreach ($a_key as &$value)
{
if($value == end($a_key) && count($a_key) != 1)
$description_get_keys = $description_get_keys.' and '.$value.'.';
else if(count($a_key) == 1)
$description_get_keys = $value.'.';
else if (count($a_key) > 1 && $a_key[0] == $value)
$description_get_keys = $value;
else
$description_get_keys = $description_get_keys.', '.$value;
}
$description = 'This is a great thing about '.$description_get_keys;
}
}
I see a couple things that could possibly be an issue, not knowing what came before this code.
I will assume that the $request variable is an instance of Illuminate\Http\Request and that it is available in the function, right?
Try this updated code:
if($request->has('description'))
{
$description = Helper::checkTextDb($request->description);
}
else if ($request->has('tags'))
{
if (strpos($request->tags, ',') === false)
{
$description = 'This is a great thing';
}
else {
$a_key = explode(",", strtolower($request->tags));
$a_count = count($a_key);
$description_get_keys = '';
for ($i = 0; $i < $a_count; $i++)
{
if ($a_count == 1) {
$description_get_keys = "{$a_key[$i]}.";
}
else {
// first
if ($i === 0) {
$description_get_keys = $a_key[0];
}
// last
else if ($i === $a_count - 1) {
$description_get_keys .= " and {$a_key[$i]}.";
}
// middle
else {
$description_get_keys .= ", {$a_key[$i]}";
}
}
}
$description = "This is a great thing about {$description_get_keys}";
}
}
I wrote that quick so hopefully there are no errors.
Currently, I program a module for Prestashop 1.6.10 which is in the administration panel, using an external API and my problem is that I don't understand how to add a product in the database in back-office.
This is the code I have wrote :
public function Product() {
if (empty($_GET['product'])) {
return false;
}
switch($_GET['product']) {
case 'add' :
$product = new ProductCore();
$product->id_shop_default = 1;
$product->id_manufacturer = 1;
$product->id_supplier = 1;
$product->reference = "adding_product";
$product->supplier_reference = "";
$product->location = "";
$product->width = "0.00000";
$product->height = "0.00000";
$product->depth = "0.00000";
$product->weight = "0.00000";
$product->quantity_discount = "0";
$product->ean13 = "0";
$product->upc = "";
$product->cache_is_pack = "0";
$product->cache_has_attachments = "0";
$product->is_virtual = "0";
$product->save();
$product->add();
break;
/** Product suppression.
case 'del' :
if (Product::existsInDatabase()) {
}
break;
}
return false;
}
I use the "product" object but it is not work and I don't why :(
Could someone help me please ?
You should use Product class instead of ProductCore.
save function is enough to save product in DB. It is not necessary to use add function after that.
If product values are incorrect it will display an error. But you should activate DEBUG MODE first: Activate Prestashop Debug Mode
Good luck.
Try using the following code.
{
$object = new Product();
foreach ($_POST as $key => $value) {
if (array_key_exists($key, $object) && $key != 'id_product') {
$object->{$key} = $value;
}
}
$languages = Language::getLanguages(false);
$class_vars = get_class_vars(get_class($object));
$fields = array();
if (isset($class_vars['definition']['fields'])) {
$fields = $class_vars['definition']['fields'];
}
foreach ($fields as $field => $params) {
if (array_key_exists('lang', $params) && $params['lang']) {
foreach ($languages as $language) {
$value = '';
if (Tools::getIsset($field . '_' . (int)$language['id_lang'])) {
$value = Tools::getValue($field . '_' . (int)$language['id_lang']);
} elseif (isset($object->{$field}[(int)$language['id_lang']])) {
$value = $object->{$field}[(int)$language['id_lang']];
}
foreach ($languages as $lang) {
if (Tools::getIsset($field . '_' . (int)$lang['id_lang']) && Tools::getValue($field . '_' . (int)$lang['id_lang']) != '')
$value = Tools::getValue($field . '_' . (int)$lang['id_lang']);
}
if ($field == 'description_short') {
$short_description_limit = Configuration::get('PS_PRODUCT_SHORT_DESC_LIMIT')
? Configuration::get('PS_PRODUCT_SHORT_DESC_LIMIT') : 400;
$object->{$field}[(int)$language['id_lang']] = strip_tags(
$this->clipLongText(
$value,
'',
$short_description_limit,
false
)
);
} else {
$object->{$field}[(int)$language['id_lang']] = $value;
}
}
}
}
foreach ($languages as $language) {
$keywords = '';
if (Tools::getIsset('meta_keywords_' . $language['id_lang'])) {
$keywords = Tools::getValue('meta_keywords_' . $language['id_lang']);
} elseif (isset($object->meta_keywords[$language['id_lang']])) {
$keywords = $object->meta_keywords[$language['id_lang']];
}
$keywords = $this->cleanMetaKeywords(
Tools::strtolower($keywords)
);
$object->meta_keywords[$language['id_lang']] = $keywords;
}
$_POST['width'] = (!Tools::getIsset('width')) ? '0' : str_replace(',', '.', Tools::getValue('width'));
$_POST['height'] = (!Tools::getIsset('height')) ? '0' : str_replace(',', '.', Tools::getValue('height'));
$_POST['depth'] = (!Tools::getIsset('depth')) ? '0' : str_replace(',', '.', Tools::getValue('depth'));
$_POST['weight'] = (!Tools::getIsset('weight')) ? '0' : str_replace(',', '.', Tools::getValue('weight'));
if (Tools::getIsset('unit_price') != null) {
$object->unit_price = str_replace(',', '.', Tools::getValue('unit_price'));
}
$object->available_for_order = (int)Tools::getValue('available_for_order');
$object->show_price = $object->available_for_order ? 1 : (int)Tools::getValue('show_price');
$object->on_sale = (int)Tools::getValue('on_sale');
$object->online_only = (int)Tools::getValue('online_only');
$ecotaxTaxRate = Tax::getProductEcotaxRate();
if ($ecotax = Tools::getValue('ecotax')) {
$_POST['ecotax'] = Tools::ps_round($ecotax / (1 + $ecotaxTaxRate / 100), 6);
}
if (Tools::getIsset('ecotax') != null) {
$object->ecotax = str_replace(',', '.', Tools::getValue('ecotax'));
}
$object->add();
}
I found a problem in my code : the function Product is not executed by the controller adminController when I click on "Adding a product" from the catalog page.
Moreover, the function works if I force Prestashop to execute the function but Prestashop don't like this because I create a bug and the module is not accessible.
[UPDATE 01-09-2017 at 17:35 GMT]
Currently, the code is working, but I have this problem now ... I think it's about the language parameters when I create the product, but I do not do what I need to do to solve this problem.
enter image description here
I'm developing a system for a client that creates a csv of packing labels which is sent to a printer. The client has six different items. Customers order products in bulk from my client. Two items (product A and product B) share the same packing line. In order to make packing more efficient my client wants to alternate between packing product A and packing product B first.
For example, if John, Sally, and James all ordered both products, the system needs to write John's orders to the csv starting with product A, Sally's orders starting with product B, and James' orders starting with product A again.
I've pasted my non-working code below, but this is really screwing with my head and I'm having a really tough time with it.
foreach($orders as $order) {
$name = null;
$phone = null;
$account = DAO_ContactPerson::get($order->account_id);
$delivery = false;
if($account->is_agency) {
$name = $order->getAttribute('name');
$phone = $order->getAttribute('phone');
} else {
$name = sprintf("%s %s",
$account->getPrimaryAddress()->first_name,
$account->getPrimaryAddress()->last_name
);
$phone = $account->phone;
}
$name = trim($name);
$phone = trim($phone);
$items = $order->getItems();
if($order->getAttribute('delivery')) {
$type = 'deliveries';
$destination = 'Delivery';
$address = sprintf("%s %s %s",
$order->getAttribute('delivery_address.line1'),
$order->getAttribute('delivery_address.line2'),
$order->getAttribute('delivery_address.postal')
);
} else {
$type = 'pickups';
$agency = DAO_ContactPerson::getAgency($order->getAttribute('pickup'));
$destination = $agency->name;
// Override account id so orders are grouped by agency
$order->account_id = $agency->id;
$address = null;
}
// var_dump($order->id);
// Init account array
if(!isset($rows[$type][$order->account_id]))
$rows[$type][$order->account_id] = array('combined' => array(), 'separate' => array());
foreach($items as $item) {
$packing = 'separated';
if($item->product_id == 3 || $item->product_id == 4)
$packing = 'combined';
if(!isset($rows[$type][$order->account_id][$packing][$item->product_id]))
$rows[$type][$order->account_id][$packing][$item->product_id] = array();
$i = 0;
while($i < $item->quantity) {
$rows[$type][$order->account_id][$packing][$item->product_id][] = array(
'number' => $order->id,
'destination' => $destination,
'size' => $item->product_id,
'name' => $name,
'address' => $address,
'phone' => $phone
);
$i++;
}
}
// if($order->id == 176) {
// var_dump($rows[$type][$order->account_id][$packing]);
// }
}
$this->weight = 1;
$pickups = count($rows['pickups']);
for($i = 0; $i < $pickups; $i++) {
$account =& $rows['pickups'][$i];
$account['output'] = array();
if(isset($account['combined'])) {
$combined_products =& $account['combined'];
if(!empty($combined_products)) {
foreach($combined_products as $prod_id => $combined) {
usort($combined_products[$prod_id], array($this, "_compareBoxes"));
}
// Flip weights once we finish with this account
$last_box = end($combined_products);
$last_box = array_pop($last_box);
reset($combined_products);
if($this->weight == 1) {
$this->weight = -1;
if($last_box['size'] == 3) {
asort($combined_products);
}
} else {
if($last_box['size'] == 4) {
arsort($combined_products);
}
$this->weight = 1;
}
foreach($combined_products as $combined) {
$account['output'][] = $combined;
}
foreach($account['separated'] as $separate) {
$account['output'][] = $separate;
}
}
} else {
if(isset($account['separated']))
$account['output'] = $account['separated'];
}
}
$deliveries = count($rows['deliveries']);
for($i = 0; $i < $deliveries; $i++) {
$account =& $rows['deliveries'][$i];
$account['output'] = array();
if(isset($account['combined'])) {
$combined_products =& $account['combined'];
if(!empty($combined_products)) {
foreach($combined_products as $prod_id => $combined) {
usort($combined_products[$prod_id], array($this, "_compareBoxes"));
}
// Flip weights once we finish with this account
$last_box = end($combined_products);
$last_box = array_pop($last_box);
reset($combined_products);
if($this->weight == 1) {
$this->weight = -1;
if($last_box['size'] == 3) {
asort($combined_products);
}
} else {
if($last_box['size'] == 4) {
arsort($combined_products);
}
$this->weight = 1;
}
foreach($combined_products as $combined) {
$account['output'][] = $combined;
}
foreach($account['separated'] as $separate) {
$account['output'][] = $separate;
}
}
} else {
if(isset($account['separated']))
$account['output'] = $account['separated'];
}
}
$rows['output'] = $rows['pickups'];
array_push($rows['output'], $rows['deliveries']);
$output = '';
foreach($rows['output'] as $account_id => $boxes) {
if(!empty($boxes['output'])) {
foreach($boxes['output'] as $labels) {
if(!empty($labels)) {
foreach($labels as $label) {
$output .= implode(',', $label) . "<br>";
}
}
}
}
}
The _compareBoxes method looks like this:
private function _compareBoxes($a, $b) {
if($a['size'] == $b['size']) {
return 0;
}
if($this->weight == 1) {
// Medium first, then Large
return ($a['size'] < $b['size']) ? -1 : 1;
}
if($this->weight == -1) {
// Large first, then Medium
return ($a['size'] > $b['size']) ? -1 : 1;
}
}