Reputation: 3
I have a foreach code which should get all the values from an array, I call the return outside the foreach loop, but even so I still get only the first value.
Here is the method I use:
public function getPriceItem($orderNumber){
try {
$query = "SELECT * FROM `orderlist` WHERE `orderNumber` = :orderNumber";
$stmt = $this->dbh->prepare($query);
$stmt->bindParam(":orderNumber", $orderNumber);
$stmt->execute();
$result = $stmt->fetchAll();
$i = 0;
$res = '';
foreach ($result as $item) {
$product_arr = explode (",", $item['productName']);
// $price_arr = explode (",", $item['productPrice']);
$qty_arr = explode (",", $item['qty']);
$res .= '<tr><td>'.$product_arr[$i].'(aantal'.$qty_arr[$i].')</td></tr>';
$i++;
}
return $res;
} catch (Exception $e) {
$this->error = $e->getMessage();
}
}
Any help would be appreciated.
Upvotes: 0
Views: 1192
Reputation: 208
I think you want all the products and its quantity related to order number. Then you need to use one more for loop inside the foreach loop. Modify you code with the code given below:
public function getPriceItem($orderNumber){
try {
$query = "SELECT * FROM `orderlist` WHERE `orderNumber` = :orderNumber";
$stmt = $this->dbh->prepare($query);
$stmt->bindParam(":orderNumber", $orderNumber);
$stmt->execute();
$result = $stmt->fetchAll();
$res = '';
foreach ($result as $item) {
$product_arr = explode (",", $item['productName']);
// $price_arr = explode (",", $item['productPrice']);
$qty_arr = explode (",", $item['qty']);
for($i=0;$i<count($product_arr) && i< count($qty_arr);i++)
$res .= '<tr><td>'.$product_arr[$i].'(aantal'.$qty_arr[$i].')</td></tr>';
}
return $res;
} catch (Exception $e) {
$this->error = $e->getMessage();
}
}
Upvotes: 0
Reputation: 3021
You don't loop through the product and qty arrays you create in your foreach, you need to traverse them as well :
foreach ($result as $item) {
$product_arr = explode (",", $item['productName']);
$qty_arr = explode (",", $item['qty']);
foreach($product_arr as $k => $product) {
$res .= '<tr><td>'.$product.'(aantal'.$qty_arr[$k].')</td></tr>';
}
}
The $i is not needed in my opinion
And that is assuming you have as many values in the product array and in the qty array. Please provide an output of your $result and your wanted output !
Upvotes: 2