php:手动创建一个数组

时间:2014-08-18 11:45:33

标签: php arrays codeigniter

新更新

你将如何编写一个输出如下的数组: Array(1) { [0]=> object(stdClass)#29 (15) { ["cals"]=> string(11) "1545.616024" } }

OLD UPDATE

如果我的数据库结果为0,我试图在数组中手动​​插入值。

我正在尝试创建一个手动数组,该数组存储值,因为此模型函数存储

public function fetch_LifeStyeActivity_byid($activityDate, $uid) {
         ----
         ----
        $query = $this->db->order_by('calorie_activity.ordering', 'ASC')->get_where('calorie_activity', array('creater_id' => $uid,'activity_date' => $activityDate, 'parent_id =' => '625'));
        $data = array();
        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $data[] = $row;
            }
            return $data;
        }
        return false;
    }

我正在像我这样的控制器这样创建它

  $data["lifeStyle_activity_query"] = array( 
    "cals"  => "6" 
);
 $this->load->view('weight_lose/activities', $data);

&安培;在查看页面时检索我正在异常

 foreach ($lifeStyle_activity_query as $row) {
  echo $row->cals;
}

获得异常:

A PHP Error was encountered

Severity: Notice

Message: Trying to get property of non-object

注意:我只需要修改控制器逻辑方面的帮助(请不要告诉我们更改视图页面代码)

1 个答案:

答案 0 :(得分:0)

您的错误只是因为您有一个数组并尝试将其用作对象。您可以将数组转换为对象,以便在视图中使用它。

$data["lifeStyle_activity_query"] = array( 
    "cals"  => "6" 
);

$data["lifeStyle_activity_query"] = (object) $data["lifeStyle_activity_query"];
echo $data["lifeStyle_activity_query"]->cals; // -> 6

编辑您的更新:

$val['cals'] = '1545.616024';
$arr[0] = (object) $val;