PHP对JSON数据格式的操作

JSON数据解码-json_decode:

<?php
// 定义一个数组变量
$fruit = array('north' => 'pear', 'shandong' => 'apple', 'hainan' => 'banana');
// 对此变量进行json编码
$json_fruit = json_encode($fruit);
//输出JSON信息
var_dump($json_fruit);
echo '<hr>';
// 输出对JSON信息反编码,并设置其返回值为array
var_dump(json_decode($json_fruit, true));

转码为JSON格式数据-json_encode:

<?php
// 关联数组
$season = array('one' => 'spring', 'two' => 'summer', 'three' => 'autumn', 'four' => 'winter');
echo json_encode($season);
echo '<hr>';
// 索引数组
$fruit = array('banana', 'apple', 'mango', 'orange');
echo json_encode($fruit);
echo '<hr>';
// 索引关联数组
$color = array('red', 'green', 'pink' => 'pink', 'purple');
echo json_encode($color);
echo '<hr>';
// 二维数组:一维是索引数组,二维是关联数组
$s1 = array('name' => 'job', 'addr' => 'America');
$s2 = array('name' => 'tom', 'addr' => 'China');
$student = array($s1, $s2);
echo json_encode($student);
echo '<hr>';
// 定义一个类
class Animal {
    public $species = 'breastfeeding';
    public $habits = 'feeding';
    public function run() {
        echo '正在跑。。。';
    }
}

$animal = new Animal;
echo json_encode($animal);

猜你喜欢

转载自blog.csdn.net/qq_42195688/article/details/80372568
今日推荐