【问题标题】:Get the next element in an array (PHP)获取数组中的下一个元素 (PHP)
【发布时间】:2015-08-03 12:05:55
【问题描述】:

我为一个数组设置了两个模型。基本上,我想要实现的是根据我设置的订单 ID 从数据库中获取第一个下一个条目。

所以,我发送了 ID 4,我找到了 ID 4 的条目,它的订单 ID 为 15。然后我想获取它之后的第一个下一个项目,它应该有订单 ID 16。我尝试使用递增在订单 ID 后 +1,但它不起作用。

使用我当前的代码,我得到了两次相同的数组。

function first($id_domain) {
        $this->db->select ( '*' );
        $this->db->from ( 'domains' );
        $this->db->where ( 'id_domain', $id_domain);
        $result = $this->db->get ();
        return $result->result_array ();

    }

    function second ($result) {
        $this->db->select ( '*' );
        $this->db->from ( 'domains' );
        $this->db->where ( 'order', $result[0]['order'] + 1 ); //code that should get me the next entry, but doesn't work...
        $this->db->where ( 'parent', $result[0]['parent'] );
        $result2 = $this->db->get ();
        return $result2->result_array ();

    }

【问题讨论】:

  • 您是否尝试打印$result[0]['order'] 以检查它是否是一个号码和您的号码?
  • 您收到数据库错误还是只有 0 个结果?如果是这样,肯定有 ID 为 3 的订单吗?还有$result[0]['parent'] 条件指的是什么?
  • 你想尝试获取下一条记录吗this->db->get()->next_record();这将返回单条记录。 codeigniter.com/user_guide/database/results.html

标签: php mysql arrays codeigniter


【解决方案1】:

问题不是由于您的代码,而可能是由于数据库中的记录:对于该特定条件它们不存在,或者您的匹配不完全正确。

如果您使用的是CodeIgniter,我建议您将second 函数更改为:

function second($result) {
    $whereConds = array(
      'order' =>  intval($result[0]['order'] + 1),
      'parent'=> $result[0]['parent']
    );
    //if you don't have firephp print/echo/var_dump as you normally would
    $this->firephp->log($whereConds);

    $query = $this->db->get_where('domains', $whereConds);

    $this->firephp->log($this->db->last_query());
    if ($query->num_rows() <= 0) {
        $this->firephp->log('No results');
        return array();
    } else {
        return $query->result_array();
    }
}

这样您可以准确地跟踪问题。

顺便说一句,您还可以使用get_where 中的$offset 参数来获取下一个id(可能只是使用父条件,因为您知道它们是按顺序排列的):

$limit=1;
$offset=intval($result[0]['order'] + 1);//adjust depending on the parent condition below: it can be just an integer such as 2
$whereConds = array(
  'parent'=> $result[0]['parent']
);
$query = $this->db->get_where('domains', $whereConds, $limit, $offset);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 2012-12-21
    • 1970-01-01
    • 2011-01-17
    • 2011-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多