【问题标题】:How to get the first data from an array如何从数组中获取第一个数据
【发布时间】:2012-08-01 05:57:09
【问题描述】:

我的 codeigniter 的视图文件中有以下代码。

<?php foreach ($records as $rows){?>
 <?  echo $rows['product_name']; ?> <br>
 <? } ?>

我的模特

 $this->db->select('*');
        $this->db->from('products');
        $this->db->order_by('product_name','ASC');
        $getData = $this->db->get('');
        if($getData->num_rows() > 0)
        return $getData->result_array();
        else
        return null;      

如果我运行上面的代码,我会得到以下结果

    Pepsi
    Coke
    Mountain Dew

我试图只显示第一个结果(百事可乐)。你能告诉我怎么做吗?

【问题讨论】:

    标签: php codeigniter-2


    【解决方案1】:

    $records 是一个数组。您可以指定索引,如

    <?=$records[0]['product_name']?>
    

    【讨论】:

      【解决方案2】:

      使用LIMIT 告诉数据库只从数据库中提取有限数量的记录

      $this->db->from('products LIMIT 0,1');
      

      【讨论】:

      • 我无法限制查询,因为我需要在同一个视图文件中的其他信息。是否可以不限制查询?谢谢:)
      【解决方案3】:

      这应该可行:

      $query = $this->db->limit(0, 1);
      

      见文档:http://codeigniter.com/user_guide/database/active_record.html

      另见:CodeIgniter Database query limit

      【讨论】:

      • 我无法限制查询,因为我需要在我的同一个视图文件中的其他信息。是否可以不限制查询?谢谢
      • 那么你可以在结果上使用方法row(),见:stackoverflow.com/questions/4280235/…
      【解决方案4】:

      reset 是解决此问题的另一种方法。 http://www.php.net/manual/en/function.reset.php

      所以在这个例子中, $first_element = reset($records);

      【讨论】:

        猜你喜欢
        • 2019-05-26
        • 2015-11-22
        • 1970-01-01
        • 2022-10-25
        • 1970-01-01
        • 1970-01-01
        • 2022-01-07
        • 2023-03-26
        • 1970-01-01
        相关资源
        最近更新 更多