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

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

WBOY
WBOYOriginal
2016-06-06 19:47:441063browse

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

 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn