2017-04-07 14 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" 

     } 
     ], 
} 
] 

私は最後の値(IDおよびNAME)を格納したいcategoryPathアレイの:

  "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は、私が機能を使用したい複数のフィールドを持っている> array-ことを考慮すると(例:エンド())のみ、最後の値の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の2番目の部分で$ sizeは検出されません。他の選択肢はより簡単でした。とてもありがとう@Augwa –