given following 2 arrays, how can merged efficiently result in third array? productdata
$productdata = [ { "product_id": 4, "type": "electronic", "name": "monitor", "specs": { "hdmi": true, "vga": false } }, { "product_id": 5, "type": "electronic", "name": "hdmi cable", "specs": { "length": "3ft" } }, { "product_id": 6, "type": "kitchen", "name": "spoon" } ]
products
$products = { "products": 3, "per_page": 10, "current_page": 1, "data": [ { "id": 4, "product_type": "electronic", "product_id": 6 }, { "id": 6, "type": "electronic", "product_id": 5 }, { "id": 9, "type": "kitchen", "product_id": 4 } ] }
productsfinal ($productdata
merged $products
- based on matching combo of product_id/product_id
, type/product_type
)
$productsfinal = { "products": 3, "per_page": 10, "current_page": 1, "data": [ { "id": 4, "product_type": "electronic", "product_id": 6, // how merge product data , wrap "data" key "data": { "product_id": 6, "type": "kitchen", "name": "spoon" } }, { "id": 6, "type": "electronic", "product_id": 5, // how merge product data , wrap in "data" key "data": { "product_id": 5, "type": "electronic", "name": "hdmi cable", "specs": { "length": "3ft" } } }, { "id": 9, "type": "kitchen", "product_id": 4, // how merge product data , wrap in "data" key "data": { "product_id": 6, "type": "kitchen", "name": "spoon" } } ] }
i tried different things outcome in foreach loop still cannot render intended:
foreach($productdata $productdataitem) { // when $productdataitem.product_id == $product.product_id && $productdataitem.type == $product.product_type // move matching $productdataitem object matching $product object, wrapped in new "data" key }
i don't know laravel well. can join data objects quite easily:
<?php $productdata = json_decode('[ { "product_id": 4, "type": "electronic", "name": "monitor", "specs": { "hdmi": true, "vga": false } }, { "product_id": 5, "type": "electronic", "name": "hdmi cable", "specs": { "length": "3ft" } }, { "product_id": 6, "type": "kitchen", "name": "spoon" } ]'); $products = json_decode('{ "products": 3, "per_page": 10, "current_page": 1, "data": [ { "id": 4, "type": "electronic", "product_id": 6 }, { "id": 6, "type": "electronic", "product_id": 5 }, { "id": 9, "type": "kitchen", "product_id": 4 } ] }'); // combine both data objects foreach($products->data &$p) { foreach($productdata $d) { if(property_exists($p, "product_id") && property_exists($d, "product_id") && property_exists($p, "type") && property_exists($d, "type")) { if($p->product_id==$d->product_id && $p->type==$d->type) { //$p = (object) array_merge((array) $p, (array) $d); $p->data = $d; // updated answer continue; } } } } echo("<pre>"); echo json_encode($products, json_pretty_print); ?>
you can test code here: http://sandbox.onlinephpfunctions.com/code/98a50c35ee32c30f0d2be1661f7afb5895174cbe update: http://sandbox.onlinephpfunctions.com/code/aeebfdcf4f4db5e960260e931982570cfed19e0e
Comments
Post a Comment