2017-04-07 431 views
1

我有产品的详细信息如下JSON文件:Laravel的PHP获得最后一个元素的多维数组

"products": [ 
    { 
     "sku": 123, 
     "name": "iphone 7", 
     "categoryPath": [ 
     { 
      "id": "abcat0800000", 
      "name": "Cell Phones" 
     }, 
     { 

      "id": "pcmcat209400050001", 
      "name": "All Cell Phones with Plans" 

     } 
     ], 
} 
] 

我想只存储最后一个值categoryPath阵列(ID和名称):

  "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) 
     )); 

考虑到基于阵列> categoryPath有多个领域,我想使用的功能(例如:结束())以只取最后一个值的ID和名称。

使用结束($ obj-> categoryPath-> ID),我收到以下错误 - >

试图修改非对象

的属性这是检索的最佳方式多维数组的最后一个值?

回答

1

你可以()可能使用结束,但你的访问者必须是结束()调用(未经测试)以外:

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 
    )); 
+0

优秀,谢谢! –

1

你得到最后一个元素的方式不正确,这里是重构的代码。我也消除了将数据作为数组投入的需要。

$json = File::get("/json/cell-0.json"); 
$data = json_decode($json, true); 
//table products 
foreach ($data['products'] as $product) { 
    $lastCategory = isset($product['categoryPath']) && $size = sizeof($product['categoryPath']) ? $product['categoryPath'][$size-1] : array('id' => null, 'name' => null); 
    DB::table('products')->insert(
     array(
      'productSku' => isset($product['sku']) ? $product['sku'] : 1, 
      'productName' => isset($product['name']) ? $product['name'] : null, 
      'categoryId' => lastCategory['id'], 
      'categoryName' => lastCategory['name'] 
     ) 
    ); 
} 
+0

我试过的例子。 $ lastCategory的第二部分未检测到$ size。另一种选择更简单。非常感谢你@Augwa –

相关问题