首页 > php教程 > php手册 > php从接口获取数据转成可以用的数组或其他(含转换编码)

php从接口获取数据转成可以用的数组或其他(含转换编码)

WBOY
发布: 2016-06-06 19:47:44
原创
1074 人浏览过

程序开发,时常会用到将接口的json数据转换成程序可以用的,因为今天看到一个比较好的程序,贴上来,以备随时查看: /* * * 将对象转成数组,并按要求转换编码 * * @param array $array 待转编码数组 * @param 标记 $flag 1为从GBK到UTF-8 0为从UTF-8到GBK *

程序开发,时常会用到将接口的json数据转换成程序可以用的,因为今天看到一个比较好的程序,贴上来,以备随时查看:

<span>/*</span><span>*
 * 将对象转成数组,并按要求转换编码
 *
 * @param array $array 待转编码数组
 * @param 标记 $flag 1为从GBK到UTF-8 0为从UTF-8到GBK
 * @return 编码后数组
 </span><span>*/</span>
<span>function</span> changeCoding(<span>$array</span>,<span>$flag</span>=<span>true</span><span>){
    </span><span>if</span>(<span>is_object</span>(<span>$array</span>)||<span>is_array</span>(<span>$array</span><span>)){
        </span><span>$array</span> = (<span>array</span>)<span>$array</span><span>;
        </span><span>foreach</span>(<span>$array</span> <span>as</span> <span>$key</span>=><span>$val</span><span>){
            </span><span>$array</span>[<span>$key</span>] = changeCoding(<span>$val</span>,<span>$flag</span><span>);
        }
    }</span><span>else</span><span> {
        </span><span>if</span>(<span>$flag</span><span>){
            </span><span>$array</span> = <span>iconv</span>('gbk','utf-8',<span>$array</span><span>);
        }</span><span>else</span><span>{
            </span><span>$array</span> = <span>iconv</span>('utf-8','gbk',<span>$array</span><span>);
        }
    }
    </span><span>return</span> <span>$array</span><span>;
}<br><br></span>
登录后复制

 初次之外,如果不用转换编码的话,可以直接用这个函数:

<span>function</span> ob2array(<span>$obj</span><span>){
    </span><span>if</span>(<span>is_object</span>(<span>$obj</span><span>)){
        </span><span>$obj</span> = (<span>array</span>)<span>$obj</span><span>;
        </span><span>$obj</span> = ob2array(<span>$obj</span><span>);
    }</span><span>elseif</span> (<span>is_array</span>(<span>$obj</span><span>)) {
        </span><span>foreach</span>(<span>$obj</span> <span>as</span> <span>$key</span> => <span>$value</span><span>){
            </span><span>$obj</span>[<span>$key</span>] = ob2array(<span>$value</span><span>);
        }
    }

    </span><span>return</span> <span>$obj</span><span>;
}</span>
登录后复制

 

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门推荐
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板