作者:_郭士铭 | 来源:互联网 | 2023-06-28 12:05
我试图获取来自请求的数据,我使用PostMan发送请求。以下数组是 dd($ items); 的输出... ...我要从这些数组中获取的数据是 id 和 quantity
array:2 [
0 => array:12 [
"id" => 4
"name" => "omnis"
"image_name" => "https://source.unsplash.com/random"
"description" => "Officiis ea provident eius perspiciatis provident et eveniet illo. Tempore ullam ab molestiae unde. Fugit pariatur consequatur sunt veritatis. Laudantium quos veritatis quasi dolorum."
"price" => 9
"discount" => 0
"status" => 1
"category_id" => 24
"place_id" => 1
"created_at" => "2019-12-15 08:05:36"
"updated_at" => "2019-12-15 08:05:36"
"quantity" => 5
]
1 => array:12 [
"id" => 5
"name" => "molestiae"
"image_name" => "https://source.unsplash.com/random"
"description" => "Debitis dignissimos est veritatis veritatis sit. Ut ex non nam aliquid dolore vero earum. Ab aliquid et quibusdam enim."
"price" => 7
"discount" => 0
"status" => 1
"category_id" => 25
"place_id" => 1
"created_at" => "2019-12-15 08:05:36"
"updated_at" => "2019-12-15 08:05:36"
"quantity" => 3
]
]
我想做foreach循环来获得这个:
{
"id":4,"quantity":5
},{
"id":5,"quantity":3
}
它尝试过:
$item_array = [];
foreach ($items as $key=>$item)
{
$item_array[$key] = $item['id'];
$item_array[$key] = $item['quantity'];
}
将循环更改为
foreach ($items as $key=>$item)
{
$item_array[$key] = array(
'id' => $item['id'],'quantity' => $item['quantity']
);
}
,
您应该这样做:
$item_array = [];
foreach ($items as $key=>$item)
{
$obj = (object) ["id"=>$item['id'],"quantity"=>$item['quantity']];
$item_array[$key]=$obj;
}
,
我要从这些数组中获取的数据是id和数量
即:
$item_array = [];
foreach ($items as $item) {
$item_array[] = [
'id' => $item['id'],'quantity' => $item['quantity']
];
}
或者如果您想使用真正的Laravel方式:
use Illuminate\Support\Arr;
$result = array_map(
function($x) {
return Arr::only($x,['id','quantity']);
},$source
);
或collect($ source)-> map(...)利用集合而不是数组。
,
use Illuminate\Support\Arr;
collect($items)->map(function($item) {
return Arr::only($item,'quantity']);
})->all();