php 中json_decode函数的用法

官方解释:json_decode — 对 JSON 格式的字符串进行编码

              接受一个 JSON 格式的字符串并且把它转换为 PHP 变量

 

 

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));
$data1=json_decode($json);
$data2=json_decode($json,true); ?>

 输出如下:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

如果第二个参数设置为true,则返回的是数组格式。默认返回的是stdClass 的对象。。。

访问方式对象模式:  $data1->a; 值为1

访问方式数组模式: $data2['a']; 值为1

 

 

注意:如果ajax采用json格式 返回的是一个json字符串,在用此函数的时候一定记的把html元素转义一下,意思就是json里面的双引号和单引号都变成了实体&quot;。需要转为".

php中可用htmlspecialchars_decode函数。

转载于:https://www.cnblogs.com/thekingofreturn/p/4803291.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果你要获取 PHP 对象(Object)的属性(Property),可以使用 PHP 的魔术方法 __get()。这个方法会在试图获取一个未定义或不可见属性时自动调用。 示例代码: ```php class MyClass { private $myProperty = 'Hello'; public function __get($name) { if (property_exists($this, $name)) { return $this->$name; } else { return null; } } } $myObject = new MyClass(); echo $myObject->myProperty; // 输出:Hello ``` 如果你需要获取对象所有属性,包括私有属性,可以使用 `get_object_vars()` 函数。示例代码: ```php class MyClass { private $myProperty = 'Hello'; public $publicProperty = 'World'; } $myObject = new MyClass(); $vars = get_object_vars($myObject); print_r($vars); ``` 输出: ``` Array ( [myProperty] => Hello [publicProperty] => World ) ``` 如果对象包含其他对象,可以使用 `json_encode()` 将对象转换为 JSON 字符串,然后再使用 `json_decode()` 将字符串转换为数组,就可以获取对象的属性了。示例代码: ```php class SubClass { public $subProperty = 'Sub Value'; } class MyClass { public $myProperty = 'My Value'; public $subObject; public function __construct() { $this->subObject = new SubClass(); } } $myObject = new MyClass(); $jsonString = json_encode($myObject); $array = json_decode($jsonString, true); print_r($array); ``` 输出: ``` Array ( [myProperty] => My Value [subObject] => Array ( [subProperty] => Sub Value ) ) ``` 注意:使用 `json_encode()` 和 `json_decode()` 转换对象时,对象的私有属性将被忽略。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值