怎么在php中利用嵌套拼接数组

发布时间:2021-03-19 16:52:21 作者:Leah
来源:亿速云 阅读:162

这篇文章给大家介绍怎么在php中利用嵌套拼接数组,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

利用嵌套 拼接数组

<?php 
 
// 自 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  包含对象数组

<?php  
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 "<pre>";  
print_r($arr);  
echo "</pre>";  
  
$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 "<pre>";  
print_r($arr);  
echo "</pre>";  
  
/************************************************************************ 
************************************************************************/  
$s='{"webname":"homehf","url":"www.homehf.com","contact":{"qq":"744348666","mail":"nieweihf@163.com","xx":"xxxxxxx"}}';  
$web=json_decode($s);  
echo '网站名称:'.$web->webname.'<br />网址:'.$web->url.'<br />联系方式:QQ-'.$web->contact->qq.' MAIL:'.$web->contact->mail;  
echo '<br /><br />';  
/************************************************************************ 
************************************************************************/  
$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 '<br /><br />';  
}  
?>

关于怎么在php中利用嵌套拼接数组就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. js如何拼接数组
  2. 怎么在python中利用字典嵌套列表

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php

上一篇:怎么在php中使用file_get_contents获取文件中的数组元素

下一篇:怎么提高php查找数组元素的效率

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》