Search code examples
phparraysloopsforeachphp-7

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"}

Then Json decode and put in print_r() I got:

stdClass Object ( [1] => 9 [3] => 7 [4] => 6 [5] => 10 [6] => 8 )
stdClass Object ( [1] => 1 [3] => 1 [4] => 1 [5] => 1 [6] => 7 )

Where in Array1 values (9, 7, 6, 10, 8) are product id and Array2 values (1,1,1,1,7) are corresponding product quantity.

Now I would like to fetch products based on products Id and want to show the corresponding quantity.

How can I do this in foreach?


Solution

  • 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
    

    Demo on 3v4l.org