我需要获取在while循环内的数组的最大值并将该值绑定到变量,但是当我尝试获取多个结果时,不仅是一个。
这是第一个表的示例,在这里我得到了需要与第二个表进行比较的当前值;
tbl name: table1
----------------------------
| id | type | category |
|----|---------|-----------|
| 1 | apple | red |
|----|---------|-----------|
| 3 | orange | yellow |
|----|---------|-----------|
| 4 | orange | red |
----------------------------
这是第二个表的示例,在这里我比较了第一个表的当前值以找出金额;
tbl name: table2
-------------------------------------
| id | type | category | amount |
|----|---------|-----------|--------|
| 1 | apple | red | 50.00 |
|----|---------|-----------|--------|
| 2 | apple | green | 75.00 |
|----|---------|-----------|--------|
| 3 | orange | yellow | 20.00 |
|----|---------|-----------|--------|
| 4 | orange | red | 20.00 |
-------------------------------------
这是我的代码;
$select_table1 = "select * from table1";
$connect_table1 = mysqli_query($con, $select_table1);
while ($row_table1 = mysqli_fetch_array($connect_table1)) {
$type = $row_table1['type'];
$category = $row_table1['category'];
$select_table2 = "select * from table2 where type in('$type') and category in('$category')";
$connect_table2 = mysqli_query($con, $select_table2);
while ($row_table2 = mysqli_fetch_array($connect_table2)) {
$amount = array(
$row_table2['amount']
);
$max = max($amount);
echo "$max<br/>";
}
}
这给了我
50.00
20.00
20.00
我自己需要的最高金额是50.00
我在做什么错了?
答案 0 :(得分:2)
将$.ajax({
url: 'url-to-get-image-api-controller',
type: 'GET',
statusCode:{
200: function(data){
$("#thumb1").html('<img src="data:image/jpg;base64,' + data + '" />');
}
}
});
与聚合函数JOIN
结合使用可获得结果。相反,它将执行一个查询,而不需要其他PHP逻辑。
MAX()
。参见SQLFiddle
答案 1 :(得分:0)
非常感谢您的创意,我使用以下方法解决了这个问题。它可能比@Qirel的答案更令人费解,但是由于我不想造成混乱,所以我没有提到额外的复杂性。例如,这些表来自2个使用特定连接的独立数据库,并且我不得不依赖变量,因为第一个表中的数据是用户创建的,并根据Cookie的值进行检索。
感谢@ rpm192,它已经差不多了。
<?php
$select_table1 = "select * from table1";
$connect_table1 = mysqli_query($con, $select_table1);
while ($row_table1 = mysqli_fetch_array($connect_table1)) {
$type = $row_table1['type'];
$category = $row_table1['category'];
$select_table2 = "select * from table2 where type in('$type') and category in('$category')";
$connect_table2 = mysqli_query($con, $select_table2);
while ($row_table2 = mysqli_fetch_array($connect_table2)) {
$amount = $row_table2['amount'];
$myArray[] = $amount;
}
}
$maxAmount = max($myArray);
echo $maxAmount;
?>