我正在尝试从一些数据数组中创建一个集合:
$myCollection = collect(
['product_id' => 1, 'price' => 200, 'discount' => '50'],
['product_id' => 2, 'price' => 400, 'discount' => '50']
);
当我循环播出时,我想这样做:
foreach ($myCollection as $product) {
echo $product->price;
echo $product->discount;
}
但是底层元素似乎仍然是数组格式,我怎样才能实现上述输出?
答案 0 :(得分:5)
如果您希望内部数组是一个集合,那么您可以按如下方式执行此操作:
$myCollection = collect([
['product_id' => 1, 'price' => 200, 'discount' => '50'],
['product_id' => 2, 'price' => 400, 'discount' => '50']
])->map(function($row) {
return collect($row);
});
如果您希望内部数组是对象,那么您可以执行以下操作:
$myCollection = collect([
['product_id' => 1, 'price' => 200, 'discount' => '50'],
['product_id' => 2, 'price' => 400, 'discount' => '50']
])->map(function($row) {
return (object) $row;
});
您还可以迭代每个结果......
$myCollection = collect([
['product_id' => 1, 'price' => 200, 'discount' => '50'],
['product_id' => 2, 'price' => 400, 'discount' => '50']
])->map(function($row) {
return (object) $row;
})->each(function($row) {
echo sprintf('ProductId: %d, Price: %d, Discount: %s'.PHP_EOL, $row->product_id, $row->price, $row->discount);
});
输出:
ProductId: 1, Price: 200, Discount: 50
ProductId: 2, Price: 400, Discount: 50
答案 1 :(得分:4)
很简单,因为您正在收集关联数组,因为您正在收集数组元素,因此集合帮助程序不需要修改它,以防您需要它作为数组。
知道这一点,如果你想收集对象,你应该传递一个对象类型的元素。
您可以将对象数据类型转换为数组,如下所示:
$myCollection = collect( (object) array(
(object) ['product_id' => 1, 'price' => 200, 'discount' => '50'],
(object) ['product_id' => 2, 'price' => 400, 'discount' => '50'])
);
然后你有一个对象的集合!
答案 2 :(得分:0)
您的集合定义中存在语法错误:
$myCollection = collect([
['product_id' => 1, 'price' => 200, 'discount' => '50'],
['product_id' => 2, 'price' => 400, 'discount' => '50']
]);
此外,由于您使用的是Collection
,因此您不再需要使用foreach
循环:
$myCollection->each(function ($item) {
echo $item['price'];
})
答案 3 :(得分:0)
函数collect()接受元素数组。您也可以通过将所有元素包含到[]中然后将Collection元素转换为对象而不是将它们保留为数组来修复代码
$myCollection = collect([
(object)(['product_id' => 1, 'price' => 200, 'discount' => '50']),
(object)(['product_id' => 2, 'price' => 400, 'discount' => '50'])
]
);
foreach ($myCollection as $product) {
echo $product->price;
echo $product->discount;
}