• 将php数组传递到js—json_encode(),json_decode()


    json_decode(),对一个json字符串进行解码,json_encode()是生成一个json字符串

    上面的解释很清楚了,关于php里数组赋值的问题,列举如下:

    <?php
    
    //对象
    class JsonTest{
    var $id = 1;
    var $name = 'heiyeluren';
    var $gender = '男';
    }
    $obj = new JsonTest;
    echo json_encode($obj)."<br />";  //{"id":1,"name":"heiyeluren","gender":"u7537"}
    
    //数字索引数组
    $arr1 = array(1, 'heiyeluren', '男');
    echo json_encode($arr1)."<br />";  //[1,"heiyeluren","u7537"]
    
    //关联索引数组
    $arr2 = array("id"=>1,"name"=>'heiyeluren',"gender"=>'男');
    echo json_encode($arr2)."<br />";  //{"id":1,"name":"heiyeluren","gender":"u7537"}
    
    //多维数字索引数组
    $arr3 = array(array(1, 'heiyeluren', '男'), array(1, 'heiyeluren', '男'));
    echo json_encode($arr3)."<br />";  //[[1,"heiyeluren","u7537"],[1,"heiyeluren","u7537"]]
    
    //关联索引数组
    $arr4 = array(array("id"=>1,"name"=>'heiyeluren',"gender"=>'男'), array("id"=>1,"name"=>'heiyeluren',"gender"=>'男'));
    echo json_encode($arr4)."<br />";  
    //[{"id":1,"name":"heiyeluren","gender":"u7537"},{"id":1,"name":"heiyeluren","gender":"u7537"}]
    ?>

    *(备注:关于在JS里调用传过来的数组的问题。可以用object的方式:obj.id、obj.name但是更多时候,它显示给我undefined,所以更推荐大家用数组的方式:obj[id]、obj[name] )


  • 相关阅读:
    栈与递归
    细说二叉树的删除操作
    二叉树
    链表队列
    数组队列
    链表栈
    c语言实现数组栈
    c语言实现双链表
    HDU 4557 非诚勿扰(Treap找后继)
    POJ 3481 Double Queue(Treap模板题)
  • 原文地址:https://www.cnblogs.com/moqiang02/p/4061402.html
Copyright © 2020-2023  润新知