【问题标题】:How to echo this multidimensional collection in laravel如何在 laravel 中回显这个多维集合
【发布时间】:2019-11-17 16:07:47
【问题描述】:

第一次来这里,是个潜伏者,搜索了很多,但这次遇到了Laravel 收藏的问题。尝试在 foreach 中回显这个多维集合数组,但我不知道如何。

我尝试过改变很多我知道的显示方式。但无济于事,希望获得一些见解,可能会改变我的方法或其他东西.. .

从数据库获取的代码

$l = [];
for($i = 0; $i < count($request->products); $i++){
    $l[] = [
          'locaction_id' => $request->products[$i]['location'],
        ];
    $locations[] = DB::table('locations')->select('*')->whereIn('location_id',$l)->get();
};

用于显示数组的代码,$location-&gt;stuff$location[0][0]['location_id'] 都试过了,出现错误

$location-&gt;location_id,输出错误:

无法找到 location_id。

$location[0][0]['location_id']$location['location_id']给出:

StdClass 错误或找不到 location_id。

foreach($locations as $key => $location){
   echo $key. "&nbsp; -" .$location->location_id. "<br>";
};

从数据库返回的数组

array:2 [▼
  0 => Collection {#662 ▼
    #items: array:1 [▼
      0 => {#660 ▼
        +"location_id": 1
        +"loc_name": "A0001"
        +"loc_desc": "Cabinet A North"
        +"created_at": "2019-07-05 10:31:12"
        +"updated_at": null
      }
    ]
  }
  1 => Collection {#688 ▼
    #items: array:1 [▼
      0 => {#686 ▼
        +"location_id": 1
        +"loc_name": "A0001"
        +"loc_desc": "Cabinet A North"
        +"created_at": "2019-07-05 10:31:12"
        +"updated_at": null
      }
    ]
  }
]

希望它能为每个数组生成循环结果。

【问题讨论】:

  • 如果是collection,您是否尝试过:$location[0]-&gt;get(0)-&gt;location_id
  • 您最好将$location 数组创建为记录数组,目前它是一个集合数组(其中包含一个数组)。
  • @dWinder 哦,谢谢,我试过了,但我得到“调用未定义的方法 stdClass::get()”
  • 能否请您添加$locationsvar_dump(在循环之后)?

标签: php arrays multidimensional-array laravel-5.7


【解决方案1】:

你可以像这样改变你的方法,

// first fetch all location ids in array
$locationIds = array_column($request->products, "location");
// pass all location ids to fetch data
$locations   = DB::table('locations')->select('*')->whereIn('location_id', $locationIds)->get();
// do foreach loop to fetch that data
foreach($locations as $key => $location){
   echo $key. "&nbsp; -" .$location->location_id. "<br>";
}

如果由于某种原因你正在编写你的 sn-p,

for ($i = 0; $i < count($request->products); $i++) {
    $l           = $request->products[$i]['location'];
    // I change it to first instead of get
    $locations[] = DB::table('locations')->select('*')->where('location_id', $l)->first();
}
// do foreach loop to fetch that data
foreach ($locations as $key => $location) {
    echo $key . "&nbsp; -" . $location->location_id . "<br>";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-19
    • 2017-04-06
    • 1970-01-01
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多