douyinjiao9351 2016-07-14 09:22
浏览 45
已采纳

通过连接2个变量创建索引变量 - php

I have a mysql query:

$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;

I will be re-using this code many times on a web-page and want to be able to run it as part of a loop.

I don't want to have to rename my variables each time (where $result_ot1 become $result_ot2 etc...)

I've tried introducing an indexing variable $x and then appending it to another variable name:

$x=2;
$result_ot.$x=....

But , it doesn't want to work.

Any suggestions? I have an idea that arrays might be needed but I'm concerned that the queries will be throwing up arrays and I'm not sure an array in an array isn't going to set my computer on fire...

  • 写回答

1条回答 默认 最新

  • duanjing7459 2016-07-14 09:53
    关注

    A hint to use your query everywhere.

    //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'];
    }
    

    And in any other place of your project:

    include 'functions.php';
    
    $total_ot1 = analyse($base, $sub, $con);
    $otper1 = ($total_ot1 / $total) * 100;
    

    I did not understand well the loop thing. But in order to dave your results in an array, you could just do this:

    $totalCounts = [];
    
    foreach(loop){
        $total_current = analyse($base, $sub, $con);
        $totalCounts[] = $total_current;
    }
    

    And you will have $totalCounts that will be an array of the query result that we find in our function. That could be a way of saving your results in an array.

    You could do it associative also:

    $x = 0;
    foreach(loop){
        $total_current = analyse($base, $sub, $con);
        $totalCounts['count_'.$x] = $total_current;
        $x++;
    }
    

    So, if you now access: $totalCounts['count_3'] you would be accessing the result of the query on the third loop, for example.

    I don't know if this is your answer. But maybe it helped a bit.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题
  • ¥15 有没有人能解决下这个问题吗,本人不会编程
  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗