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 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)