How to get corresponding value of key from two arrays in foreach
I have the following arrays in JSON encode:
Array1 {"1":"9","3":"7","4":"6","5":"10","6":"8"}
Array2 {"1":"1","2":"1","3":"1","4":"1","5":"1","6":"7"}
Where in Array1 values (9, 7, 6, 10, 8) area unit product id and Array2 values (1,1,1,1,7) area unit corresponding product amount.
Now I might wish to fetch merchandise supported merchandise Id and need to indicate the corresponding amount.
How am I able to do that in foreach?
Dominic
With a simple foraech and a check if the product Id exists :
$productId = json_decode(‘{“1″:”9″,”3″:”7″,”4″:”6″,”5″:”10″,”6″:”8”}’, true);
$productQuantity = json_decode(‘{“1″:”1″,”2″:”1″,”3″:”1″,”4″:”1″,”5″:”1″,”6″:”7”}’, true);
foreach($productId as $id) {
$quantity = “?”; //if id not exists
if(array_key_exists($id, $productQuantity)) {
$quantity = $productQuantity[$id];
}
echo “productId: “.$id.” Quantity:”.$quantity.”
\n”;
}
Robert Niro
By setting the $assoc parameter to json_decode to true, we can convert the JSON values into arrays rather than objects, and then iterate through the product_id array, finding matching quantities from the second array:
$j1 = ‘{“1″:”9″,”3″:”7″,”4″:”6″,”5″:”10″,”6″:”8”}’;
$j2 = ‘{“1″:”1″,”2″:”1″,”3″:”1″,”4″:”1″,”5″:”1″,”6″:”7”}’;
$array1 = json_decode($j1, true);
$array2 = json_decode($j2, true);
foreach ($array1 as $key => $product_id) {
$quantity = $array2[$key] ?? 0;
echo “Product $product_id: Quantity: $quantity\n”;
}
By setting the $assoc parameter to json_decode to true, we can convert the JSON values into arrays rather than objects, and then iterate through the product_id array, finding matching quantities from the second array:
$j1 = ‘{“1″:”9″,”3″:”7″,”4″:”6″,”5″:”10″,”6″:”8”}’;
$j2 = ‘{“1″:”1″,”2″:”1″,”3″:”1″,”4″:”1″,”5″:”1″,”6″:”7”}’;
$array1 = json_decode($j1, true);
$array2 = json_decode($j2, true);
foreach ($array1 as $key => $product_id) {
$quantity = $array2[$key] ?? 0;
echo “Product $product_id: Quantity: $quantity\n”;
}
Output:
Product 9: Quantity: 1
Product 7: Quantity: 1
Product 6: Quantity: 1
Product 10: Quantity: 1
Product 8: Quantity: 7