I have a Json File with the following structure:
"products": [
{
"sku": 3953367,
"productId": 1219609308595,
"name": "Samsung - Galaxy Core Prime 4G LTE with 8GB Memory Cell Phone - Charcoal gray (Verizon)",
"relatedProducts": [
{
"sku": 7664117
},
{
"sku": 2819038
},
{
"sku": 4806009
}
],
"salesRankShortTerm": 14593,
}
]
To store those details and import the data to a mysql database i created 2 tables:
- table products (for sku, productID, name and salesRankShortTerm.)
- table products_related (for relatedProducts and each Sku of products related to the main product)
My idea is to insert into:
- Table products: create a record of ->sku and productname. eg: 3953367, "Samsung - Galaxy Core Prime 4G LTE with 8GB Memory Cell Phone - Charcoal gray (Verizon)"
- Table products_related: create a record of ->sku (same field as sku in products table) and each Sku of relatedproducts. eg: 3953367, 7664117.
I created the following code:
$json = File::get("/json/cell-1.json");
$data = json_decode($json);
$array1 = (array) $data;
// foreach to import into table products
foreach ($array1['products'] as $obj) {
DB::table('products')->insert(array(
'productName' => ((isset($obj->name) ? $obj->name : null)),
'productSku' => ((isset($obj->sku) ? $obj->sku : 1)),
..etc
));
// foreach to import into table products_related
foreach ($array1['products'] as $obj2) {
DB::table('products_related')->insert(array(
'productId' => ((isset($obj2->sku) ? $obj2->sku : null)),
'sku' => ((isset($obj2->relatedProduct->sku) ? $obj2->relatedProduct->sku : null))
));
}
}
information contained in array1 as $obj1 -> worked perfect, each product (sku, productID, name and salesRankShortTerm) is stored in products table.
details in array1 as $obj2 -> not working ok. each product sku is stored in products related table but not each relatedProducts->sku. its like the foreach of "relatedProducts": [] is not taken into consideration. Additionally if I write $array1['products']['relatedProducts'] the code response is [ErrorException] Undefined Index: relatedProducts.
My question are:
its possible to store all the information in different tables in one run process?
or
I have to import first the information to products and then: use each sku of products table to retrieve and save each sku of relatedProducts into products_related table?
any help appreciated.
via s_h