[Untested]
Something like this?
$skus = array();
$list = $db->loadAssocList();
foreach ($list as $entry) {
if (!isset($skus[$entry['product_id']])) $skus[$entry['product_id']]
= array();
$skus[$entry['product_id']][] = $entry['product_sku'];
}
foreach ($skus as $product_id => $codes) {
$upsql = "update #__vm_product set
custom_attribute='".implode(';',$codes).
"' where product_id=".$product_id;
$db->setQuery($upsql);
$db->query();
}
Or... if you don't want to buffer the data for the entire list at
once...
function sku_update($id, $codes) {
$upsql = "update #__vm_product set
custom_attribute='".implode(';',$codes).
"' where product_id=".$id;
$db->setQuery($upsql);
$db->query();
}
$buffer_codes = array();
$buffer_id = null;
foreach ($list as $entry) {
if ($buffer_id != $entry['product_id']) {
if (isset($buffer_id)) sku_update($buffer_id, $buffer_codes);
$buffer_id = $entry['id'];
$buffer_codes = array();
}
$buffer_codes[] = $entry['product_sku'];
}
sku_update($buffer_id, $buffer_codes);
On Feb 19, 10:54 am, Jochen Daum <[email protected]> wrote:
> Hi,
> I have a common piece of code below and I wonder if this can be done more
> elegantly. The code below reads records from a database - in this example a
> product_id and lots of skus that represent variations of this product. It
> then implodes all skus of a product into a field in another table. This is
> done for each product_id.
>
> I know this can be done with less lines of code by using @, condensing if
> statements and accepting that it throws E_NOTICE some times. But aside from
> that, can it be done completely diferently and more elegantly.
>
> I'm seeing myself writing this piece of code over and over, covering
> database queries or converting one array structure into another.
>
> BTW, database layer is from Joomla, but could be any database layer.
>
> Cheers,
> Jochen
>
> $db =& JFactory::getDBO();
>
> $sql = 'select product_id, product_sku from
> #__vm_product_selecon_product_codes '.
> 'order by product_id, product_sku ';
> $db->setQuery($sql);
>
> $list = $db->loadAssocList();
>
> $last_pid = 0;
> $first = 1;
> $imp=array();
> if ($list){
> foreach ($list as $entry){
> if ($entry['product_sku'] && !in_array($entry['product_sku'],
> $imp)){
> $imp[] = $entry['product_sku'];
> }
> if (!$first){
> if ($last_pid != $entry['product_id']){
> $upsql = "update #__vm_product set
> custom_attribute='".implode(';',$imp).
> "' where product_id=".$last_pid;
> $db->setQuery($upsql);
> $db->query();
> $imp=array();
> $last_pid = $entry['product_id'];
> }
> }else{
> $first = 0;
> }
> }
> }
>
> }
--~--~---------~--~----~------------~-------~--~----~
NZ PHP Users Group: http://groups.google.com/group/nzphpug
To post, send email to [email protected]
To unsubscribe, send email to
[email protected]
-~----------~----~----~----~------~----~------~--~---