php对json数据迭代,【PHP】json数据操作总结

哀差闷最近在写一个天查询的API,将已有的api服务重新封装下。其中涉及到一些json数据的操作问题,特此记录一下。

json_encode函数 中文乱码

使用json_encode函数将数组转换为json数据时会出现中文乱码。原因时json_encode只支持UTF-8的编码,但是,在实际使用的过程还是会出现乱码。解决方法如下。先对要转换成json的数组使用urlencode函数进行转换,然后再把转换成json数据的字符串使用urldecode解一下。但是urlencode支持单个字符的转换,所以需要另外构造一个函数:/**************************************************************

*

* 使用特定function对数组中所有元素做处理

* @param string &$array 要处理的字符串

* @param string $function 要执行的函数

* @return boolean $apply_to_keys_also 是否也应用到key上

* @access public

*

*************************************************************/

function arrayRecursive(&$array, $function, $apply_to_keys_also = false)

{

static $recursive_counter = 0;

if (++$recursive_counter > 1000) {

die('possible deep recursion attack');

}

foreach ($array as $key => $value) {

if (is_array($value)) {

$this->arrayRecursive($array[$key], $function, $apply_to_keys_also);

} else {

$array[$key] = $function($value);

}

if ($apply_to_keys_also && is_string($key)) {

$new_key = $function($key);

if ($new_key != $key) {

$array[$new_key] = $array[$key];

unset($array[$key]);

}

}

}

$recursive_counter--;

}

使用示例$weatherArr为待转换的数组:$this->arrayRecursive($weatherArr, 'urlencode', true);

$weather_json = json_encode($weatherArr);

echo urldecode($weather_json);

当然也可以自己使用foreach遍历整个数据,类似如下:foreach($value as $k => $v)

{

$value[$k] = urlencode($v);

}

json_decode

使用json_decode将json数据转换为数组时一定得使用第二个参数为true,不然转换的不是标准的Php数组。例如:$weatherArr = json_decode($weather_json, true);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值