首页 > 解决方案 > 如何从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中做到这一点?

标签: phparraysloopsforeachphp-7

解决方案


使用简单的 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";
}

返回

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

推荐阅读