jarvis Posted March 18, 2019 Share Posted March 18, 2019 Hi All, I've a loop which creates an array as follows: $product_table[] = ['SKU' => $sku, 'Label' => $attribute_name, 'Value' => $term_obj->name ]; I'm then grouping the data by SKU code: #group the products by SKU $group_products = array(); foreach ($product_table as $element) : $group_products[$element['SKU']][] = $element; endforeach; Finally, I output the data: #output the data foreach ($group_products as $itemName => $rows) : echo '<tr>'; #echo '<td>', $element['SKU'], '</td>'; $i=0; foreach ($rows as $row) : $i++; #echo '<td>'. $row["SKU"]. '</td><td>'. $row["Label"]. '</td><td>'. $row["Value"]. '</td>'; if ($i == 1): echo '<td>'. $row["SKU"]. '</td><td>'. $row["Value"]. '</td>'; else: echo '<td>'. $row["Value"]. '</td>'; endif; #echo '<td>'. $row["Value"]. '</td>'; endforeach; echo '</tr>'; endforeach; ?> And looks like: Product code System Pack Quantity XT1CWH System 1 1 x 3m XT2CWH System 2 1 x 3m XT3CWH System 3 1 x 3m This works perfectly fine. However, some products share the same SKU and therefore it causes an issue, like the below: Product code System Pack Quantity XT1CLWH System 1 8 x 3m System 2 8 x 3m System 3 8 x 3m Is there a way I can avoid this, so if perhaps creates the new row but shows the same SKU code? Many thanks Quote Link to comment Share on other sites More sharing options...
taquitosensei Posted March 18, 2019 Share Posted March 18, 2019 $group_products = array(); foreach ($product_table as $element) : if(!isset($product_table[$element['SKU']])) { $group_products[$element['SKU']][] = $element; } endforeach; Quote Link to comment Share on other sites More sharing options...
ginerjm Posted March 18, 2019 Share Posted March 18, 2019 If this is a repetitive project that is going to build all of the mentioned arrays every time it is executed, perhaps you should consider not having to re-build your second array by using the SKU as the index value of the first array and avoid creating the 2nd array. Change this: $product_table[] = ['SKU' => $sku, 'Label' => $attribute_name, 'Value' => $term_obj->name ]; to: $product_table[$sku][] = ['Label' => $attribute_name, 'Value' => $term_obj->name ]; 2 Quote Link to comment Share on other sites More sharing options...
Psycho Posted March 20, 2019 Share Posted March 20, 2019 In addition to ginerjm's excellent suggestion on building the array one time, the output code is also inefficient. This would do the same with much less code and in a more logical format. #output the data foreach ($product_table as $sku => $products) { echo "<tr>\n"; echo "<td>{$sku}</td>\n"; foreach ($products as $product) { echo "<td>{$row['Value']}</td>\n"; } echo "</tr>\n"; } Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.