Foreach循环$ key => $值

时间:2015-01-18 20:22:19

标签: php foreach

$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包含Qty列的ID和值显示值 所以问题是:

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

1 个答案:

答案 0 :(得分:0)

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

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