I have two variables, number and user, which are not fixed. When I iterate through the array below, how do I determine if the number and user criteria are met to get the appropriate ID
Example:
If the value of amount is 100 and the value of user is 6, then the obtained ID is 1;
If the value of amount is 50000 and the value of user is 10, the obtained ID is also 1;
If the value of amount is 50000 and the value of user is 12, the obtained ID is also 2;
Why do I always get 1?
$amount = 10000;
$user = 12;
$id = null;
foreach ($array as $item) {
if ($amount >= $item['value']['amount']['min'] && $user >= $item['value']['user']['min']) {
$id = $item['id'];
break;
}
}
echo $id;
The array as follows:
$array = [
[
'id' => 1,
'value' => [
'amount' => [
'min' => 100,
'max' => 9999
],
'user' => [
'min' => 5,
'max' => 10
],
'ratio' => 10
]
],
[
'id' => 2,
'value' => [
'amount' => [
'min' => 10000,
'max' => 49999
],
'user' => [
'min' => 11,
'max' => 30
],
'ratio' => 30
]
],
[
'id' => 3,
'value' => [
'amount' => [
'min' => 50000,
],
'user' => [
'min' => 50,
],
'ratio' => 35
]
]
];
My Answer:
= $item['amount'] && $user == $item['user']) {
$id = $item['id'];
break;
}
}
This code snippet iterates through the array and checks if the current item's 'amount' and 'user' values match the given $amount and $user variables. If a match is found, the corresponding 'id' value is assigned to the $id variable and the loop is exited using the 'break' statement.
If you are always getting 1 as the result, it could be due to the fact that the conditions in the if statement are not being met for the given $amount and $user values. Make sure that the values in the array match the values you are checking for in the loop.
Rate this post
3 of 5 based on 5641 votesComments