Reputation: 223
I have one loop for appending some strings to a variable. I need a best way of doing same. Currently I am pushing everything to an array then I implode it with comma. Is there any other best way of doing the same? Here is my code
$getDataProduct = "SELECT pm.*,crm.id sub_id, crm.name sub_name FROM `cp_reference_master` crm
LEFT JOIN product_master pm on crm.parent_id = pm.category
Where crm.mode = 'item_type_subcat' AND pm.id = ".$data['id'];
$logger->debug("Get Product From Product Master for ".$data['id']);
$logger->trace("Query: ".$getDataProduct);
$result = $db->func_query($getDataProduct);
//echo '<pre>'; print_r($result); echo '</pre>';
foreach($result as $details){
$result[0]['sub_ids'] = $details['sub_id'];
$result[0]['sub_names'] = $details['sub_name'];
}
In my query I am getting 3 or 4 rows. except sub_id and sub_name everything is same. I need to append this sub_id and sub_name and put it in first row of sub_id and sub_name
Upvotes: 1
Views: 5210
Reputation: 23968
Not sure this is the correct place your problem is but I will give it a try.
foreach($result as $details){
$result_ids .= "," . $details['sub_id'];
$result_sub_names .= "," . $details['sub_name'];
}
This will create a comma first so you need to clear that with:
$result_sub_names = substr($result_sub_names,1);
Upvotes: 3
Reputation: 200
$getDataProduct = "SELECT pm.*,crm.id sub_id, crm.name sub_name FROM `cp_reference_master` crm
LEFT JOIN product_master pm on crm.parent_id = pm.category
Where crm.mode = 'item_type_subcat' AND pm.id = ".$data['id'];
$logger->debug("Get Product From Product Master for ".$data['id']);
$logger->trace("Query: ".$getDataProduct);
$result = $db->func_query($getDataProduct);
$sub_ids = '';
$sub_names = '';
foreach($result as $details){
$sub_ids = $sub_ids.', '. $details['sub_id'];
$sub_names = $sub_names.', '. $details['sub_name'];
$result[0]['sub_ids'] = $details['sub_id'];
$result[0]['sub_names'] = $details['sub_name'];
}
Now Every thing int the $sub_ids and $sub_names, no need to implode array with comma.
Upvotes: 0