-1

伙计们,这是完整的代码:

   $response = $this->db->select('DATE(`created_at`) as `day`')->select('MIN(`paid_amount`) as `min_amount`')->select('MAX(`paid_amount`) as `max_amount`')->get('orders');

$nation = array();
foreach ($response->result() as $row)
{
    print_r((array)$row);
    array_push($nation, (array)$row);
}

我得到了 print_r 的输出,如下所示:

   Array
    (
        [day] => 2013-03-24
        [min_amount] => 2.00
        [max_amount] => 2.00
        [avg_amount] => 2.000000
        [total_revenue] => 2.00
        [total_orders] => 1
        [total_subscriptions] => 0
        [total_refunds] => 0
        [refunded_amount] => 1.00
    )

我使用了下面的forloop,但它没有工作。如何遍历这个数组:

foreach($nation as $key=>$value)
{
      echo $key;
}
4

4 回答 4

2

尝试这个:

foreach($nation as $key=>$value)
{
      echo $key." = ".$value;
      echo "<br />";
}

那应该输出:

 day = 2013-03-24
 min_amount = 2.00
 max_amount = 2.00
 avg_amount = 2.000000
 total_revenue = 2.00
 total_orders = 1
 total_subscriptions = 0
 total_refunds = 0
 refunded_amount = 1.00

如果没有打印出来,则表示数组$nation为空。您也可以通过以下方式确认

print_r($nation);

编辑

看到您更新的问题后,这应该可以解决问题:

foreach($nation as $array)
{
   echo $array['day'];
   echo '<br />';
   echo $array['min_amount'];
   echo '<br />';
   .
   .
   .
    and so on
}
于 2013-06-13T08:09:08.893 回答
0

您正在使用 array_push() 将行输入 $nation。每行将从 0 、 1 、 2 等编号。如果您只有 1 行,您将只有 item 0。那就是0你所看到的。

你实际上需要这样做:

foreach($nation as $row) // getting the rows you entered with array_push(). In your case now it's just 1.
{
    foreach($row as $key=>$value) // getting the fields in each row
    {
        echo $key; // getting the field name. (Use $value if you want the field data.)
    }
}
于 2013-06-13T08:14:40.447 回答
0

不确定您是如何声明数组的,但请参见下文:

$nation = array (
    'day' => 2013-03-24,
    'min_amount' => 2.00,
    'max_amount' => 2.00,
    'avg_amount' => 2.000000,
    'total_revenue' => 2.00,
    'total_orders' => 1,
    'total_subscriptions' => 0,
    'total_refunds' => 0,
    'refunded_amount' => 1.00,
);

foreach ($nation as $key=>$value) {
    echo $key . '<br>';
}
于 2013-06-13T08:09:32.930 回答
0

您的数组看起来已经打印出来了。

试试看var_dump($nation);会出现什么 - 你的$nation可能不是数组或未设置。

它应该看起来像这样:

$nation = array (
    'day'                  => 2013-03-24,
    'min_amount'           => 2.00,
    'max_amount'           => 2.00,
    'avg_amount'           => 2.000000,
    'total_revenue'        => 2.00,
    'total_orders'         => 1,
    'total_subscriptions'  => 0,
    'total_refunds'        => 0,
    'refunded_amount'      => 1.00
);

打印出来:

foreach($nation as $key => $value){
    echo $key.' -> '.$value.'<br/>';
}
于 2013-06-13T08:11:13.683 回答