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

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

WBOY
WBOYoriginal
2016-06-06 19:47:441073parcourir

程序开发,时常会用到将接口的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>

 

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn