首页 > 语言 > PHP > 正文

PHP实现数组转JSon和JSon转数组的方法示例

2024-05-05 00:04:14
字体:
来源:转载
供稿:网友

本文实例讲述了PHP实现数组转JSon和JSon转数组的方法。分享给大家供大家参考,具体如下:

数组转JSon数据:

$array_1 = array(); //一维数组$array_2 = array(); //多维数组$array_1['username']='ericwolf';$array_1['age']=25;$array_2['menber']['aa']['username']='ericwolf';$array_2['menber']['aa']['age']=25;$array_2['menber']['bb']['username']='eeee';$array_2['menber']['bb']['age']=22;print_r($array_2);$jsonObj_1 = json_encode($array_1);var_dump($jsonObj_1);$jsonObj_1 = json_encode($array_2);var_dump($jsonObj_1);

运行结果:

Array
(
    [menber] => Array
        (
            [aa] => Array
                (
                    [username] => ericwolf
                    [age] => 25
                )
            [bb] => Array
                (
                    [username] => eeee
                    [age] => 22
                )
        )
)
string(32) "{"username":"ericwolf","age":25}"
string(84) "{"menber":{"aa":{"username":"ericwolf","age":25},"bb":{"username":"eeee","age":22}}}"

JSon转数组,并打印:

$jsonStr = '{"key":"value","key1":"value1"}';$json2Array = json_decode($jsonStr,true);foreach($json2Array as $key=>$val) {  echo $key."=".$val."<br/>";}

运行结果:

key=value
key1=value1


注:相关教程知识阅读请移步到PHP教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选