【问题标题】:Arrays and loops through days数组和循环通过天
【发布时间】:2013-08-16 23:07:22
【问题描述】:

我在创建此函数时遇到问题。我的代码一团糟,我被卡住了,所以我宁愿不发布它。我宁愿寻求新的解决方案。

我有一个数组(mysql 行),以今天的日期作为条件。我想根据前一个数组中的数据创建一个新数组,并在今天之前将其插入数据库。限制为 15。因此,如果到此日期已经有 10 行,则仅插入 5 行,并在下一个日期继续,只要第一个数组中有行。

我正在使用 php 和代码点火器。

【问题讨论】:

  • 你卡在哪个方面?如何查询数据?如何计算结果?如何创建特定数量的新条目?如何将这些新条目重新插入数据库?
  • 我被困在我想说的创建循环和条件上。查询数据插入回数据库就OK了。

标签: php arrays codeigniter loops


【解决方案1】:

我不知道您是如何获取数据或如何生成新数据的,但类似这样;

//loop through days that you want to check/update
    //fetch existing data for this day into $data
    if( count( $data ) >= 15 ) continue; //skip days that already have 15+
    for( $x = 0; $x < 15 - count( $data ); $x++ )
    {
        //insert one new row here
    }
//end days loop

【讨论】:

  • 谢谢您。你能告诉我如何在这里发布一段代码吗?(我是新手)然后我会发布我的代码以便更容易理解。
  • 每行缩进自动变成代码。 4 个空格缩进 :) 您还可以将句子中间的小位标记为 this 之类的代码,方法是用两个反引号(波浪号键上的那个)围绕它。
  • 这就是我获取数据的方式:$subscriptions = Subscription::all(array('conditions' =&gt; 'token != "" ')); 开始时间是 $startTime = strtotime('today'); ,采用 Y-m-d 格式。现在我想要实现的是遍历所有订阅,处理它,然后插入另一个表。我正在检查它:$projects = Project::all(array('conditions' =&gt; 'end = "'.date("Y-m-d", $startTime).'" ')); 所以如果那天没有项目或 $startTime = strtotime('+1 day', $startTime);。
【解决方案2】:

这就是我的做法,它做了我想做的事。不确定这是否是实现此功能的最佳方式。在这里,我使用一个临时数组来进行测试。每个元素将是数据库的新行。仅在测试时使用 3 作为最大值(而不是 15)。

    $subscriptions = Subscription::all(array('conditions' => 'token != "" ', 'order' => 'id asc'));
    $startTime = strtotime('2013-08-15'); 

    $temparray = array();

    $projects = Project::all(array('conditions' => 'end = "'.date("Y-m-d", $startTime).'" '));
    if ($projects){$counter = count($projects);}else{$counter = 0;}

    while (list($key, $value) = each($subscriptions))
    {
        if ($counter == 3)
        {
            do
            {
                $startTime = strtotime('+1 day', $startTime);
                $projects = Project::all(array('conditions' => 'end = "'.date("Y-m-d", $startTime).'" '));
                if (count($projects) < 3)
                    {
                        $counter = count($projects);
                        break;
                    }
            } while ($counter <= 3);

                $temparray[] = $value->date . " " . date("Y-m-d", $startTime);
                continue;   
        }

    $temparray[] = $value->date . " " . date("Y-m-d", $startTime);
    $counter++;
    }

【讨论】:

    猜你喜欢
    • 2017-03-13
    • 2019-04-19
    • 2017-03-21
    • 2012-09-16
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多