php - 在 laravel 中附加 JSON 数组的 url
问题描述
我的 MySQL 表列中有一个 JSON 字段,其中包含一个带有部分图像 URL 的 JSON 数组。
"images": [
{
"images": {
"original": "/storage/uploads/1.png",
"300": "/storage/uploads/300.1.png",
"600": "/storage/uploads/600.1.png",
"900": "/storage/uploads/900.1.png"
},
"thumb": "/storage/uploads/300.1.png"
},
{
"images": {
"original": "/storage/uploads/2.png",
"300": "/storage/uploads/300.2.png",
"600": "/storage/uploads/600.2.png",
"900": "/storage/uploads/900.2.png"
},
"thumb": "/storage/uploads/300.2.png"
},
{},
]
我想通过为数组的每个值附加一个基本 URL 来获取数组。
"images": [
{
"images": {
"original": "http://localhost:8000/storage/uploads/1.png",
"300": "http://localhost:8000/storage/uploads/300.1.png",
"600": "http://localhost:8000/storage/uploads/600.1.png",
"900": "http://localhost:8000/storage/uploads/900.1.png"
},
"thumb": "http://localhost:8000/storage/uploads/300.1.png"
},
{
"images": {
"original": "http://localhost:8000/storage/uploads/2.png",
"300": "http://localhost:8000/storage/uploads/300.2.png",
"600": "http://localhost:8000/storage/uploads/600.2.png",
"900": "http://localhost:8000/storage/uploads/900.2.png"
},
"thumb": "http://localhost:8000/storage/uploads/300.2.png"
},
{},
]
我已经尝试过像下面的代码那样使用 Collections 函数。但是没有成功。
'images' => collect($item->images)->map(function ($image) {
return url($image);
})->all(),
解决方案
您可以使用嵌套的 foreach 来解决这个问题
$json = json_decode($item->images, true); // I'm using true to convert the json to array
$images = [];
foreach ($json as $index => $array) {
foreach ($array as $key => $value) {
if (is_array($value)) {
foreach ($value as $path_key => $path) {
$images[$index][$key][$path_key] = url($value[$path_key]);
}
} else {
$images[$index][$key] = url($value);
}
}
}
如果dd($images);
你会得到
array:2 [▼
0 => array:2 [▼
"images" => array:4 [▼
"original" => "http://localhost:8000/storage/uploads/1.png"
300 => "http://localhost:8000/storage/uploads/300.1.png"
600 => "http://localhost:8000/storage/uploads/600.1.png"
900 => "http://localhost:8000/storage/uploads/900.1.png"
]
"thumb" => "http://localhost:8000/storage/uploads/300.1.png"
]
1 => array:2 [▼
"images" => array:4 [▼
"original" => "http://localhost:8000/storage/uploads/2.png"
300 => "http://localhost:8000/storage/uploads/300.2.png"
600 => "http://localhost:8000/storage/uploads/600.2.png"
900 => "http://localhost:8000/storage/uploads/900.2.png"
]
"thumb" => "http://localhost:8000/storage/uploads/300.2.png"
]
]
推荐阅读
- excel - 在 Excel 中偏移 Vlookup 值
- node.js - MongoDB基于嵌套数组比较用户
- wordpress - 为什么在向链接添加一些字符时,WordPress 不会给出 404 错误?
- r - R插入符号:train()因带有因子预测器的repeatcv而失败
- sql - Oracle SQL“先连接”用于获取继承权限
- ruby-on-rails - Rails 使用 ISO-8859-1 编码而不是 UTF-8 加载 ActiveSupport 正则表达式
- xcode - 如何在 swift 中使用“touches started”方法调整库对象的大小
- javascript - 如何自定义复制到剪贴板按钮
- php - 在 WooCommerce 管理订单中保存选择选项可编辑字段
- sql-server - SSRS 表达式在字段中切换姓氏、名字到名字姓氏