【问题标题】:PHP iterate through array with dictionaryPHP用字典遍历数组
【发布时间】:2018-06-30 13:08:06
【问题描述】:

您好,我是 php 新手,我有一个类似于以下代码的数组。

 [ { "amount" : "204", "order" : "15", "customer": "12"}, { "amount" : "208", "order" : "17", "customer": "18"},{ "amount" : "300", "order" : "15", "customer": "19"} ]

如何迭代并获得所有金额?尝试使用 foreach 并以我使用的无效参数结束。

   $xabo = [ { "amount" : "204", "order" : "15", "customer": "12"}, { "amount" : "208", "order" : "17", "customer": "18"},{ "amount" : "300", "order" : "15", "customer": "19"} ] 
   foreach($xabo as $denge){
   print_r $denge['amount'];
   } 

【问题讨论】:

标签: php arrays sorting dictionary


【解决方案1】:

这是一个 JSON 编码的数组。您需要将其定义为字符串并对其进行解码。对于 print_r,您还需要括号。

 $xabo_str = '[ { "amount" : "204", "order" : "15", "customer": "12"}, { "amount" : "208", "order" : "17", "customer": "18"},{ "amount" : "300", "order" : "15", "customer": "19"} ]';
 $xabo = json_decode($xabo_str, true);
 foreach($xabo as $denge){
   print_r($denge['amount']);
 } 

json_decode 中的 true 确保您只获取数组。这样您就可以使用 array['key'] 语法访问密钥。

【讨论】:

  • "JSON 编码数组" 这不是编码数组。这是一个简单的 JSON 字符串,而不是数组。如果您实际使用 json_encode() 将其转换回来,则会对其进行编码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-14
  • 2015-05-19
相关资源
最近更新 更多