获取数组中的下一个元素(PHP)

时间:2015-08-03 12:05:55

标签: php mysql arrays codeigniter

我为阵列设置了两个模型。基本上,我想要实现的是根据我设置的订单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 ();

    }

1 个答案:

答案 0 :(得分:0)

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

如果您使用的是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();
    }
}

通过这种方式,您可以准确地跟踪问题。

顺便说一下,您还可以使用$offset中的get_where参数来获取下一个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);