如何从foreach中的两个数组中获取对应的键值

How to get corresponding value of key from two arrays in foreach

我在 json 编码中有以下数组:

Array1 {"1":"9","3":"7","4":"6","5":"10","6":"8"}
Array2 {"1":"1","2":"1","3":"1","4":"1","5":"1","6":"7"}

然后Json解码并放入print_r() 我得到了:

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

其中Array1中的值(9, 7, 6, 10, 8)是产品id,Array2中的值(1,1,1,1,7)是对应的产品数量。

现在想根据商品Id去抓取商品,并显示对应的数量。

如何在 foreach 中执行此操作?

https://www.php.net/manual/en/function.array-combine.php

$string1 = '{"1":"9","3":"7","4":"6","5":"10","6":"8"}';
$string2 = '{"1":"1","2":"1","3":"1","4":"1","5":"1","6":"7"}';
$array1 = json_decode($string1, true);
$array2 = json_decode($string2, true);

// Filter arrays to keep only those keys that both have in common
$filtered1 = array_intersect_key($array1, $array2);
$filtered2 = array_intersect_key($array2, $array1);

// Create new array with $filtered1 as keys and $filtered2 as values
$newArray = array_combine($filtered1, $filtered2);

// Test
$exampleId = 7;
$exampleQuantity = $newArray[$exampleId]; // Outputs 1

可以有多个实现:

您可以在 foreach 循环中使用 array_search

或者您可以使用 array_combine,其中 return 您是一个包含产品 => 数量

的新数组

使用简单的 foraech 并检查产品 ID 是否存在:

$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."<br>\n";
}

returns

productId: 9 Quantity:?
productId: 7 Quantity:?
productId: 6 Quantity:7
productId: 10 Quantity:?
productId: 8 Quantity:?

通过将$assoc参数设置为json_decode为true,我们可以将JSON值转换为数组而不是对象,然后遍历product_id数组,从第二个数组中找到匹配数量:

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

输出:

Product 9: Quantity: 1
Product 7: Quantity: 1
Product 6: Quantity: 1
Product 10: Quantity: 1
Product 8: Quantity: 7

Demo on 3v4l.org