Php 在laravel集合对象中添加新元素

Php 在laravel集合对象中添加新元素,php,laravel,laravel-5,Php,Laravel,Laravel 5,我想在$items数组中添加新元素,由于某些原因,我不想使用联接 $items = DB::select(DB::raw('SELECT * FROM items WHERE items.id = '.$id.' ;')); foreach($items as $item){ $product = DB::select(DB::raw(' select * from product where product_id

我想在
$items
数组中添加新元素,由于某些原因,我不想使用联接

$items = DB::select(DB::raw('SELECT * FROM items WHERE items.id = '.$id.'  ;'));
        foreach($items as $item){
            $product = DB::select(DB::raw(' select * from product
                   where product_id = '. $id.';' ));

            $item->push($product);
        }

我该怎么办呢?

看起来你所有的东西都是正确的,但是你有一个打字错误

$item->push($product);
应该是

$items->push($product);
我还想知道,您正在寻找的实际方法是
put

$items->put('products', $product);

如上所述,如果要将查询的集合添加为新元素,可以使用:

    $items = DB::select(DB::raw('SELECT * FROM items WHERE items.id = '.$id.'  ;'));
    foreach($items as $item){
        $product = DB::select(DB::raw(' select * from product
               where product_id = '. $id.';' ));

        $items->push($product);
        // or 
        // $items->put('products', $product);
    }
但是,如果希望向每个查询的元素添加新元素,则需要执行以下操作:

    $items = DB::select(DB::raw('SELECT * FROM items WHERE items.id = '.$id.'  ;'));
    foreach($items as $item){
           $product = DB::select(DB::raw(' select * from product
                 where product_id = '. $id.';' ));
    
          $item->add_whatever_element_you_want = $product;
    }

add\u which\u element\u you\u所需
可以是您希望命名的元素的任何名称(例如产品)。

如果您使用两个表的数组,我已经解决了这个问题。你的例子,
$tableA['yellow']
$tableA['blue']
。您将获得这两个值,并希望在其中添加另一个元素,以按其
类型将其分隔开

foreach ($tableA['yellow'] as $value) {
    $value->type = 'YELLOW';  //you are adding new element named 'type'
}

foreach ($tableA['blue'] as $value) {
    $value->type = 'BLUE';  //you are adding new element named 'type'
}

因此,如果要将项添加到集合的开头,这两个表值都将具有名为
type

的新元素,您可以使用:

foreach ($tableA['yellow'] as $value) {
    $value->type = 'YELLOW';  //you are adding new element named 'type'
}

foreach ($tableA['blue'] as $value) {
    $value->type = 'BLUE';  //you are adding new element named 'type'
}

如果要将产品添加到阵列中,可以使用:

    $items = DB::select(DB::raw('SELECT * FROM items WHERE items.id = '.$id.'  ;'));
    foreach($items as $item){
        $product = DB::select(DB::raw(' select * from product
               where product_id = '. $id.';' ));

        $items->push($product);
        // or 
        // $items->put('products', $product);
    }
$item['product']=$product;

使用
Push
方法将新元素添加到集合中,例如
$items->Push(您可以在此处数组) Laravel可能会考虑调用类似于“代码> PuthHouKEY(…)< /代码>)来帮助理解清楚。