【发布时间】:2017-09-02 05:23:10
【问题描述】:
我有以下包含产品详细信息的 json 文件:
"products": [
{
"sku": 123,
"name": "iphone 7",
"categoryPath": [
{
"id": "abcat0800000",
"name": "Cell Phones"
},
{
"id": "pcmcat209400050001",
"name": "All Cell Phones with Plans"
}
],
}
]
我只想存储 categoryPath 数组的最后一个值(ID 和 NAME):
"id": "pcmcat209400050001", "name": "All Cell Phones with Plans"
我当前的代码获取 json 文件,解码 json 并在产品表中插入信息。
$json = File::get("/json/cell-0.json");
$data = json_decode($json);
$array1 = (array)$data;
//table products
foreach ($array1['products'] as $obj) {
DB::table('products')->insert(array(
'productSku' => ((isset($obj->sku) ? $obj->sku : 1)),
'productName' => ((isset($obj->name) ? $obj->name : null)),
'categoryId' => end($obj->categoryPath->id),
'categoryName' => end($obj->categoryPath->name)
));
考虑到 array->categoryPath 有多个字段,我想使用一个函数(例如:end())来获取最后一个值的 id 和 name。
使用 end($obj->categoryPath->id) 我收到以下错误 ->
尝试修改非对象的属性
这是检索多维数组最后一个值的最佳方法吗?
【问题讨论】: