• 数组和json的相互转换


    json_encode()

    <?php
    
    /*****一维数组*********/
    //有键
    $arr = array(
    	'a'=>1, 
    	'b'=>2,
    	'c'=>3,
    );
    $json = json_encode($arr);
    echo($json);  //{"a":1,"b":2,"c":3}
    
    //无键
    $arr = array(1,2,3);
    $json = json_encode($arr);
    echo($json);  //[1,2,3]
    
    /*****二维数组*********/
    //有键
    $arr = array(
    	'a' => array('id'=>1, 'xuefei'=>"100" ), 
    	'b' => array('id'=>2, 'xuefei'=>"200" ),
    	'c' => array('id'=>3, 'xuefei'=>"300" ),
    );
    $json = json_encode($arr);
    echo($json);  //{"a":{"id":1,"xuefei":"100"},"b":{"id":2,"xuefei":"200"},"c":{"id":3,"xuefei":"300"}}
    
    //无键
    $arr = array(
    	array('id'=>1, 'xuefei'=>"100" ), 
    	array('id'=>2, 'xuefei'=>"200" ),
    	array('id'=>3, 'xuefei'=>"300" ),
    );
    $json = json_encode($arr);
    echo($json);  //[{"id":1,"xuefei":"100"},{"id":2,"xuefei":"200"},{"id":3,"xuefei":"300"}]
    
    ?>

    json_decode

    <?php
    
    /*****一维json*********/
    //有键
    $json = '{"a":1,"b":2,"c":3}'; //不加key的话输出null
    $arr = json_decode($json);
    var_dump($arr);
    /*
    输出:
    object(stdClass)[1]
      public 'a' => int 1
      public 'b' => int 2
      public 'c' => int 3
    */ 
    
    //无键
    $json = '["a","b","c"]';  //加key的话输出null
    $arr = json_decode($json);
    var_dump($arr);
    /*
    输出:
    array (size=3)
      0 => string 'a' (length=1)
      1 => string 'b' (length=1)
      2 => string 'c' (length=1)
    */
    
    /*****二维json*********/
    //有键
    $json = '{"a":{"id":1,"xuefei":"100"},"b":{"id":2,"xuefei":"200"},"c":{"id":3,"xuefei":"300"}}';
    $arr = json_decode($json,true);
    var_dump($arr);
    /*
    输出:
    array (size=3)
      'a' => 
        array (size=2)
          'id' => int 1
          'xuefei' => string '100' (length=3)
      'b' => 
        array (size=2)
          'id' => int 2
          'xuefei' => string '200' (length=3)
      'c' => 
        array (size=2)
          'id' => int 3
          'xuefei' => string '300' (length=3)
    */ 
    
    //无键
    $json = '[{"id":1,"xuefei":"100"},{"id":2,"xuefei":"200"},{"id":3,"xuefei":"300"}]';
    $arr = json_decode($json,true);
    var_dump($arr);
    /*
    输出:
    array (size=3)
      0 => 
        array (size=2)
          'id' => int 1
          'xuefei' => string '100' (length=3)
      1 => 
        array (size=2)
          'id' => int 2
          'xuefei' => string '200' (length=3)
      2 => 
        array (size=2)
          'id' => int 3
          'xuefei' => string '300' (length=3)
    */ 
    
    ?>



  • 相关阅读:
    IE10/IE9 Click Enter will trigger submission
    错误代码以及错误消息提示-如何更好地管理与维护消息资源
    Redmine2.6.1 升级与Agile插件安装
    编译安装的 mysql apache 用 service mysqld start 来启动
    编译安装php 5.5 缺少依赖包 及解决方案
    linux 下mysql的启动 、调试、排错
    linux 的 磁盘操作
    mysql 触发器的创建 修改 删除
    创建mysql存储过程,调用 及删除
    存储函数的创建 删除 修改
  • 原文地址:https://www.cnblogs.com/moqiang02/p/4061185.html
Copyright © 2020-2023  润新知