我是从 Laravel 开发 ِAPi 的新人,我需要将路径应用程序插入到值数组中
$halls = DB::table('halls')
->join('imagas','halls.id','=','imagas.id_Halls')
->select('halls.id','halls.hall_name','halls.hall_adress','halls.hall_details','price_hours','price_int','halls.hall_name','imagas.image_path')
->where('halls.id',157)
->get();
$results = [];
foreach ($halls as $hall) {
$array = json_decode($hall->image_path, true);
if (is_array($array)) {
$hall->image_path = 'http://127.0.0.1:8000/Imaga_halls/' . $array;
}
array_push($results, $hall);
}
return response()->json($results);
错误是
ErrorException:数组到字符串的转换
$hall->image_path = 'http://127.0.0.1:8000/Imaga_halls/'.$array;
您正在尝试将数组连接到此处的字符串。
在查询生成器上的
get()
方法之后,您将获得集合,以便您可以使用 map()
函数循环每个 hall
对象。
并将前缀路径与图像连接起来:
$halls = DB::table('halls')
->join('imagas','halls.id','=','imagas.id_Halls')
->select('halls.id','halls.hall_name','halls.hall_adress','halls.hall_details','price_hours','price_int','halls.hall_name','imagas.image_path')
->where('halls.id',157)
->get();
$results = $halls->map(function($hall) {
$array = json_decode($hall->image_path, true);
$hall->image_path = collect($array)->map(function($image) {
return 'http://127.0.0.1:8000/Imaga_halls/'.$image;
})->toArray();
return $hall;
});
return response()->json($results);
对
json_decode()
进行映射调用,然后使用 substr_replace()
在图像文件名前添加完整路径,然后将新数据合并到原始行中。 PHPize 演示
return response()->json(
DB::table('halls')
->join('imagas', 'halls.id', '=', 'imagas.id_Halls')
->select(
'halls.id',
'halls.hall_name',
'halls.hall_adress',
'halls.hall_details',
'price_hours',
'price_int',
'halls.hall_name',
'imagas.image_path'
)
->where('halls.id', 157)
->get()
->map(
fn($obj) => array_replace(
(array) $obj,
['image_path' => substr_replace(
json_decode($obj->image_path, true),
'http://127.0.0.1:8000/Imaga_halls/',
0,
0
)]
)
)
);
打印漂亮的回复:
[
{
"id": 157,
"hall_name": "ali",
"hall_adress": "st-50",
"hall_details": null,
"price_hours": "3000",
"price_int": "500",
"image_path": [
"http:\/\/127.0.0.1:8000\/Imaga_halls\/1579635535.jpg",
"http:\/\/127.0.0.1:8000\/Imaga_halls\/1579635536.jpg",
"http:\/\/127.0.0.1:8000\/Imaga_halls\/1579635537.png",
"http:\/\/127.0.0.1:8000\/Imaga_halls\/1579635538.png"
]
}
]