i have a query inside a for loop that getting the product name of every array element. Now in every element of my array, i have an ID, where i want to concat all product names with the-same shipping_id.
Here i have my array with values like these:
Array name:id
with values of:
Array
(
[0] => Array
(
[product_id] => 1
[shipping_id] => 1
)
[1] => Array
(
[product_id] => 2
[shipping_id] => 1
)
[2] => Array
(
[product_id] => 1
[shipping_id] => 2
)
)
now i made this code with these:
$first = true;
$temp_ship_id = "";
$product_list = "";
foreach ($ids as $product) {
$productname = $this->getproductname($product[0][product_id]);
// if($first) {
// $temp_ship_id = $product[0][shipping_id];
// $first = false;
// }
// if($product[0][shipping_id] == $temp_ship_id) {
// $product_list .= $productname.";
// } else {
// $product_list .= $productname.";
// //$product_list = "";
// $temp_ship_id = $product[0]->shipping_id;
// }
}
public function getproductname($product_id) {
$product = DB::table('products')->select('product_name')
->where(['products.product_id'=>$product_id])
->first();
return $product->product_name;
}
what am i doing is, i am getting the first shipping id and store it and i made a condition if they are thesame then i go concat the productname but, i see my logic is bad.
Please help me in other way. Something like This line of code to begin with:
foreach ($ids as $product) {
$productname = $this->getproductname($product[0][product_id]);
//code for concat goes here
}
public function getproductname($product_id) {
$product = DB::table('products')->select('product_name')
->where(['products.product_id'=>$product_id])
->first();
return $product->product_name;
}