【问题标题】:Codeigniter - passing multiple values to viewCodeigniter - 传递多个值来查看
【发布时间】:2012-12-16 22:07:02
【问题描述】:

好的,所以一般来说我这样做不会有问题,而且会相当简单,但这次不是那么多。

这是我的控制器中的相关代码:

// In order to properly build the form url, we need to include the
                // category and product to the view
                $this->data = array(
                        'category' => $category,
                        'product' => $product
                        );

                // Load the product model and get editable values from the database
                $this->load->model('productadmin/products_model');
                $productInformation = $this->products_model->get_product_data($product);

                // Modular code! Use variable-variables to prevent having to write multiple lines of code
                // when we start returning more information from the data
                foreach ( $productInformation as $variable => $value )
                {
                    $this->data[$variable] = $value;
                }

现在,理想情况下,我应该能够访问 $product、$category 以及从 products 模型返回的任何变量。做一个 print_r,我得到以下信息:

Array ( [category] => 1 [product] => 1 [0] => Array ( [id] => 1 [product_name] => Duff ) )

注意 foreach 语句生成的内容是如何包含在它自己的数组中的。最简单的解决方案是知道如何从视图中访问第二个数组,只需传递$this->data

如果这不可行,我可以改变什么来在数据数组中分配模型的关联值而不在其中创建另一个数组?

模型只是从 get_where 语句返回键值对。

【问题讨论】:

    标签: php codeigniter activerecord view controller


    【解决方案1】:

    在将数据传递到视图之前,您应该为数据使用关联数组。尝试更改此行:

    foreach ( $productInformation as $variable => $value )
    {
      $this->data[$variable] = $value;
    }
    

    用这个:

    foreach ( $productInformation as $variable => $value )
    {
      $this->data['product_information'][$variable] = $value;
    }
    

    然后在您的视图中,您可以使用$product_information 变量访问您的产品信息。

    注意:我假设您使用以下方式将数据传递给视图:

    $this->load->view('your_view', $this->data);
    

    【讨论】:

    • 这实际上对我不起作用。创建以下数组: Array ( [category] ​​=> 1 [product] => 1 [product_information] => Array ( [0] => Array ( [id] => 1 [product_name] => Duff ) ) )它无法通过 $product_information['product_name'];
    • 您可以通过 $product_information[0]['product_name'] 或 foreach 数组访问它: foreach($product_information as $pi) { echo $pi['product_name']; }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-27
    • 2021-12-05
    • 1970-01-01
    相关资源
    最近更新 更多