php - 如何从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中做到这一点?
解决方案
使用简单的 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:?
推荐阅读
- python - 如何知道从特定方法调用了多少次方法
- r - r ls list.files 模式大括号扩展通配符不起作用
- angular - Angular 7 - 从子组件发出的事件不调用父组件函数
- linux - 如何在谷歌计算引擎中使用 tar.gz 文件加载 docker 镜像?
- emacs - 如何在公司完成菜单中两次触发 company-show-doc-buffer?
- python-3.x - 反向循环列表,删除元素
- ruby-on-rails - Ruby on Rails - 结合 #or 和 #joins
- google-cloud-platform - 为什么 GCP 存储桶上的新文件不发送 pubsub 消息?
- javascript - 如何使用 Json 内部的数据?
- javascript - 如何让 Discord Bot 做出多种不同的响应?