如何在Codeigniter中合并数组

时间:2014-02-18 05:56:24

标签: php codeigniter

在控制器中:

public function subscription(){
        $this->load->model('ar/LogSubscriptionAR');
        $sub = $this->LogSubscriptionAR->merge('admin_contact','category')->get()->result_array();
        $this->load->view('admin/log/subscription',compact('sub','sub'));
    }

我在列表视图中有3个对象

我想显示管理员:John Doe,如果是admin-1和

显示所有类别ID 1 show tour_package:欧洲,如果类别ID 31 显示航班:如果类别ID为-1,则全部

<tr class="data-template">          
            <td data-name="type"></td>
            <td data-name="name"></td>
            <td data-name="category"></td>
            <td data-name="admin_contact_selector"></td>            
</tr>

2 个答案:

答案 0 :(得分:0)

如果这只是单个数组条目,那么你可以尝试这个,否则你必须为完整的数组集应用循环

$result[] = $array1[0] + $array2[0];

// print_r($result );

it will give you output

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Alice
            [age] => 1
        )

)

另一种方法是循环遍历第二个结果数组并将值添加到第一个数组。

// Get products results as an array
$this->db->select('products.title,
                   products.description,
                   products.price,
                   products.stock');
$this->db->from('products');
$this->db->where('product_id', $id);
$product = $this->db->get()->result_array();

// Get product attributes as an array
$this->db->select('name, value');
$this->db->from('product_attributes');
$this->db->where('product_id', $id);
$product_attributes = $this->db->get()->result_array();

// Loop through the results
foreach($product_attributes as $attribute) {

     // Add results to original product array
     $product[$attribute['name']] = $attribute['value'];
}

这应该产生一个这样的数组:

    [title]       => Modest Swimsuit - Full body 
    [description] => UV +50 Protection - Chlorine Resistant - Water Resistant - Quick Drying - Maximum Breathe Ability- Sea Water Resistant 
    [price]       => 59.95 
    [stock]       => 20
    [Brand]       => Modestly Active Swimwear 
    [Colour]      => Black and Light Blue
    [size]        => small

答案 1 :(得分:0)

$query = $this->db->query("SELECT * FROM food_items JOIN categories ON food_items.item_category=categories.category_id AND food_items.item_status='1'");
        $result = array();
        foreach ($query->result_array() as $value) {
            $result[] = array_merge($value,array("foo"=>"foo")); 
        }
    print_r($result);

输出:

        [id] => 1
        [item_id] => ITEM34
        [item_name] => 
        [item_type] => Regular
        [item_price] => 0
        [item_description] => 
        [item_qty] => 0
        [item_status] => 1
        [last_modified] => 22-07-2017 09:47:06am
        [foo] => foo

这对我很有用!!!

相关问题