I have this foreach
foreach ($categoryArr as $key => $value) {
foreach ($biciCorretta as $chiave => $valore) {
$biciSingola = $valore;
$contatoreqty =1;
if ($biciSingola->category_id = $key && $contatoreqty <= $value) {
if (!in_array($biciSingola,$biciSelezionata, true)) {
array_push($biciSelezionata, $biciSingola);
}
$contatoreqty ;
}
}
echo "$contatoreqty <br>";
}
this is dd $categoryAarr:
array:1 [▼
1 => "1"
]
to be precise
array:1 [▼
1(category id) => "1"(quantity request)
]
this is the dd of $biciCorretta (are the bikes I have in that category):
array:2 [▼
0 => App\Models\Bike {#1461 ▶}
1 => App\Models\Bike {#1459 ▶}
]
if the category of the single bike is correct and the quantity ($ value) is less than or equal to the counter push the bike into the array.
I expect there is only one bike in the $biciSelezionata array as the quantity required is only one instead the result is the following:
array:2 [▼
0 => App\Models\Bike {#1461 ▶}
1 => App\Models\Bike {#1459 ▶}
]
CodePudding user response:
there is a problem on your condition
if ($biciSingola->category_id = $key && $contatoreqty <= $value) {
The condition here must be ==
Write if ($biciSingola->category_id == $key && $contatoreqty <= $value) {
instead
And its important where you initiate your $contatoreqty variable. it will always be 1 if condition fails