【问题标题】:Foreach loop $key => $valueForeach 循环 $key => $value
【发布时间】:2015-01-18 20:22:18
【问题描述】:
$suggestions = array();

    $this->db->from('items');
    $this->db->where('deleted',0);
    $this->db->like('name', $search);
    $this->db->limit($limit);
    $by_name = $this->db->get();

    $temp_suggestions = array();

    foreach($by_name->result() as $row)
    {
        if ($row->category && $row->size)
        {
            $temp_suggestions[$row->item_id] =  $row->name . ' ('.$row->category.', '.$row->size.')'.' Unit Price: '. $row->unit_price;
        }
        elseif ($row->category)
        {
            $temp_suggestions[$row->item_id] =  $row->name . ' ('.$row->category.')'.' Unit Price: '.$row->unit_price;
        }
        elseif ($row->size)
        {
            $temp_suggestions[$row->item_id] =  $row->name . ' ('.$row->size.')'.' Unit Price: '.$row->unit_price;
        }
        else
        {
            $temp_suggestions[$row->item_id] = $row->name.' Unit Price: '.$row->unit_price;         
        }

    }

    asort($temp_suggestions);

    foreach($temp_suggestions as $key => $value)
    {
        $suggestions[]=array('value'=> $key, 'label' => $value); // Please take a look at this line     
    }

您好,请参阅注释行,foreach 循环仅显示 9 列中的 2 列,它们是键和值。 key 包含 ID 和 values 显示 Qty 列的值 所以问题是:

如何修改此 foreach 循环以使用 foreach 循环获取所有查询列?

【问题讨论】:

  • 也许在循环之前做一个print_r($temp_suggestions) 并写下输出。
  • @gmk: 不,在 PHP 中 $a[] = item; 总是会向数组中添加一个新项目。
  • 嗨 gmk,我不需要最后一列

标签: php foreach


【解决方案1】:

变量$temp_suggestions 包含,而不是。要从每一行获取所有数据,您必须在前面的循环中将该数据插入$temp_suggestions。例如,要将所有列作为由 item_id 索引的逗号分隔列表返回:

foreach($by_name->result() as $row) {
    $temp_suggestions[$row->item_id] = implode(', ', (array) $row);
}

【讨论】:

  • 嗨,Peter Gluck,它可以工作,但是如何访问每一行?谢谢
猜你喜欢
  • 2023-02-05
  • 2022-01-23
  • 2011-03-19
  • 1970-01-01
  • 2012-09-02
  • 1970-01-01
  • 2020-11-14
  • 1970-01-01
  • 2013-08-31
相关资源
最近更新 更多