dousui6193
2015-03-06 01:58
浏览 29

使用带有1d和2d数组的php json_decode

I am using json_decode in PHP to decode a JSON object which may have 1d array or 2d array for a value:

{"Cell":{"@column":"ZjE6dW5pdmVyc2l0eQ==","@timestamp":"1425598820484","$":"MC44MDc2NDEwNDg0MjI5MjMy"}}

or

{"Cell":[{"@column":"ZjE6YQ==","@timestamp":"1425599309809","$":"MC4wNTYzMzgwMjgxNjkwMTQwODY="},{"@column":"ZjE6YW5k","@timestamp":"1425599309809","$":"MC4wNTYzMzgwMjgxNjkwMTQwODY="},{"@column":"ZjE6Y2F0Y2hlcw==","@timestamp":"1425599309809","$":"MC4wNDIyNTM1MjExMjY3NjA1Ng=="},{"@column":"ZjE6aQ==","@timestamp":"1425599309809","$":"MC4wOTg1OTE1NDkyOTU3NzQ2NA=="},{"@column":"ZjE6dGhhdA==","@timestamp":"1425599309809","$":"MC4xNjkwMTQwODQ1MDcwNDIyNQ=="}]}

and I am using $Cell = $json["Cell"] to access the elements. The problem I am facing is that the second case plays nicely and I get an array of arrays while the first one should be a single element array but is being interpreted as a 3 element array.

图片转代码服务由CSDN问答提供 功能建议

我在PHP中使用json_decode解码一个JSON对象,该对象可能有1d数组或2d数组的值: / p>

 <代码> { “小区”:{ “@列”: “ZjE6dW5pdmVyc2l0eQ ==”, “@时间戳”: “1425598820484”, “$”: “MC44MDc2NDEwNDg0MjI5MjMy”}} 
    
 
 

 <代码> { “小区”:[{ “@列”: “ZjE6YQ ==”,“@ 时间戳 “:” 1425599309809" , “$”: “MC4wNTYzMzgwMjgxNjkwMTQwODY =”},{ “@列”: “ZjE6YW5k”, “@时间戳”: “1425599309809”, “$”: “MC4wNTYzMzgwMjgxNjkwMTQwODY =”},{“@柱 “:” ZjE6Y2F0Y2hlcw == “ ”@时间戳“: ”1425599309809“, ”$“: ”MC4wNDIyNTM1MjExMjY3NjA1Ng ==“},{ ”@列“: ”ZjE6aQ ==“, ”@时间戳“: ”1425599309809“,”  $ “:” MC4wOTg1OTE1NDkyOTU3NzQ2NA == “},{” @列 “:” ZjE6dGhhdA ==”, “@时间戳”: “1425599309809”, “$”: “MC4xNjkwMTQwODQ1MDcwNDIyNQ ==”}]} 
  <  / pre> 
 
 

我使用$ Cell = $ json [“Cell”]来访问元素。 我面临的问题是第二种情况很好,我得到一个数组数组,而第一种应该是单个元素数组,但被解释为3元素数组。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • drz5553 2015-03-06 02:16
    已采纳

    Can't you just check if the element has the key? Like this:

    if (isset($json['Cell']['@column']) {
        // do stuff with single-element
    } else {
        // it is a collection
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题