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

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

WBOY
Lepaskan: 2016-06-06 19:47:44
asal
1069 orang telah melayarinya

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

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

<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>
Salin selepas log masuk

 

sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Cadangan popular
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan