php返回json套数组_利用php嵌套数组拼接并解析json

本篇文章主要介绍了php利用嵌套数组拼接与解析json的方法,内容挺不错的,现在分享给大家,也给大家做个参考。

利用嵌套数组 拼接混合json -包含对象数组

// 自 PHP 5.4 起

$array = [

"status" => "0",

"message" => "ok",

"arr"=> []

];

class Person {

public $name;

public $age;

//定义一个构造方法初始化赋值

public function __construct($name,$age) {

$this->name=$name;

$this->age=$age;

}

}

for($i=0;$i<10;$i++)

{

$p=new Person("ren",$i);

$array["arr"][]=$p;

}

//var_dump($array);

echo json_encode($array);

?>

php利用嵌套数组 解析混合json 包含对象数组

function json_to_array($web) {

$arr=array();

foreach($web as $k=>$v) {

if(is_object($v)) $arr[$k]=json_to_array($v); //判断类型是不是object

else $arr[$k]=$v;

}

return $arr;

}

$s='{"webname":"homehf","url":"www.homehf.com","qq":"744348666"}';

//将字符转成JSON

$web=json_decode($s);

$arr=array();

foreach($web as $k=>$v)

$arr[$k]=$v;

echo "

";

print_r($arr);

echo "

";

$s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"744348666","mail":"nieweihf@163.com","xx":"xxxxxxx"}}';

$web=json_decode($s);

$arr=json_to_array($web);

echo "

";

print_r($arr);

echo "

";

/************************************************************************

************************************************************************/

$s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"744348666","mail":"nieweihf@163.com","xx":"xxxxxxx"}}';

$web=json_decode($s);

echo '网站名称:'.$web->webname.'
网址:'.$web->url.'
联系方式:QQ-'.$web->contact->qq.' MAIL:'.$web->contact->mail;

echo '
';

/************************************************************************

************************************************************************/

$s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"744348666","mail":"nieweihf@163.com","xx":"xxxxxxx"}}';

$web=json_decode($s);

echo json_encode($web);

$mys='{"status":"0","message":"ok","arr":[{"name":"ren","age":0},{"name":"ren","age":1},{"name":"ren","age":2},

{"name":"ren","age":3},{"name":"ren","age":4},{"name":"ren","age":5},{"name":"ren","age":6},{"name":"ren","age":7},

{"name":"ren","age":8},{"name":"ren","age":9}]}';

$myweb=json_decode($mys);

echo $myweb->status;

for($i=0;$i<10;$i++)

{

echo $myweb->arr[$i]->age;

echo '
';

}

?>

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值