[英]Creating an indexed variable by concatenating 2 variables - php
我有一个mysql查询:
$analyse_ot1="SELECT COUNT(*) AS ot_count FROM first, base, users
WHERE base.base_id=$base
AND
users.base_id=$base
AND
users.id=first.user_id
AND
first.$sub='OT'";
$result_ot1=mysqli_query($con,$analyse_ot1);
$row_ot1= mysqli_fetch_assoc($result_ot1);
$total_ot1= $row_ot1['ot_count'];
$otper1=($total_ot1/$total)*100;
我将在网页上多次重复使用此代码,并希望能够将其作为循环的一部分运行。
我不想每次都重命名变量(其中$ result_ot1变为$ result_ot2等)
我尝试引入索引变量$ x,然后将其附加到另一个变量名称:
$x=2;
$result_ot.$x=....
但是,它并不想工作。
有什么建议么? 我有一个可能需要数组的想法,但是我担心查询将抛出数组,而且我不确定数组中的数组不会使我的计算机着火...
可以在任何地方使用查询的提示。
//declare this in a folder, 'functions.php', for example
function analyse($base, $sub, $con)
{
$analyse_ot1 = 'SELECT COUNT(*) AS ot_count FROM first, base, users'
." WHERE base.base_id=$base AND users.base_id=$base"
." AND users.id=first.user_id AND first.$sub='OT'";
$result_ot1 = mysqli_query($con, $analyse_ot1);
$row_ot1 = mysqli_fetch_assoc($result_ot1);
return $row_ot1['ot_count'];
}
在项目的任何其他位置:
include 'functions.php';
$total_ot1 = analyse($base, $sub, $con);
$otper1 = ($total_ot1 / $total) * 100;
我对循环事情不太了解。 但是为了将结果放入数组中,您可以这样做:
$totalCounts = [];
foreach(loop){
$total_current = analyse($base, $sub, $con);
$totalCounts[] = $total_current;
}
您将拥有$totalCounts
,这将是我们在函数中找到的查询结果的数组。 那可能是将结果保存在数组中的一种方法。
您也可以将其关联:
$x = 0;
foreach(loop){
$total_current = analyse($base, $sub, $con);
$totalCounts['count_'.$x] = $total_current;
$x++;
}
因此,例如,如果现在访问: $totalCounts['count_3']
,则将在第三个循环上访问查询结果。
我不知道这是否是您的答案。 但也许有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.