遍历php中的JSON对象 [英] Iterate through JSON object in php

查看:107
本文介绍了遍历php中的JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

   echo $_COOKIE[$cart_cookie]; //prints   "[{\"id\":1353,\"product\":\"prod23\",\"quantity\":1,\"price\":43},{\"id\":133453,\"product\":\"prod\",\"quantity\":1,\"price\":23}]"
   $json_data = json_decode($_COOKIE[$cart_cookie]);
            echo $json_data; // prints [{"id":1353,"product":"prod23","quantity":1,"price":43},{"id":133453,"product":"prod","quantity":1,"price":23}]
            foreach ($json_data as $item) { // Warning: Invalid argument supplied for foreach() 


            }

有人可以建议,在php中迭代JSON时我会缺少什么?当我得到警告:运行此代码时,为foreach()提供的参数无效.

Could anyone suggest, what am I missing while iterating JSON in php ? As I'm getting Warning: Invalid argument supplied for foreach() when running this code.

推荐答案

JSON字符串格式错误.就像addslashes的效果一样,它已经被引用并且里面的引号已被转义.

The JSON string has a wrong format. It has been quoted and quotes inside it have been escaped, like would have been the effect of addslashes.

您的代码无法揭示这种篡改发生的位置,但是最好是消除这种情况的原因.如果您的PHP版本低于5.4,请打开 magic_quots_gpc 配置关闭.

Your code does not reveal where this tampering happened, but it would be best you would remove the cause of this. If your version of PHP is below 5.4, then please turn the magic_quots_gpc configuration off.

但是鉴于当前情况,您可以按如下所示将字符串修复回有效的JSON:

But given the current situation, you can fix the string back to valid JSON as follows:

$json_data = json_decode(stripslashes(trim($_COOKIE[$cart_cookie],'"')));

因此,应用了两个功能:

So, there are two functions applied:

  • trim(..., '"'):从字符串中删除第一个和最后一个字符,即换行双引号;

  • trim(..., '"'): removes the first and last character from the string, i.e. the wrapping double quotes;

stripslashes(...):取消转义字符串中转义的所有内容,例如双引号.

stripslashes(...): un-escapes whatever was escaped inside your string, e.g. the double quotes.

这篇关于遍历php中的JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆