PHP – json_encode 與 json_decode , 取出物件或陣列的方式
<?
//class用法
class a{
public $first = "chang";
public $second = array(second_a => "HAPPY", second_b => "NEW YEAR" );
public $third = array();
//一旦建立class時,把class b 塞進 $third 陣列, 但會在陣列$third[0]底下…. 當json_decode會很麻煩
function __construct(){
$third = array_push($this->third,new b);
}
}
class b {
public $third_a = "HELLOW WORD";
public $third_b = "WELLOW TAIWAN";
}
//編碼
$result_en = json_encode(new a);
//用物件取出
$result = json_decode($result_en);
print_r($result->first); // 輸出chang
echo "<br>";
print_r($result->second->second_a); // 輸出 HAPPY
echo "<br>";
//要取出third_a還是用json_decode返回陣列取出來吧
$result = json_decode($result_en,true);
print_r($result['third'][0]['third_a']); // 輸出 HELLOW WORD
echo "<br>";
echo "——————-<br>";
//普通陣列用法
$array = array(first => "a", second => array(second_a => "GOOD MORNING", second_b => "GOOD NIGHT" ));
$array = json_encode($array);
//解碼
$result = json_decode($array);
print_r($result->first); //輸出a
echo "<br>";
print_r($result->second->second_a); //輸出GOOD MORNING
echo "<br>";
//解碼(返回陣列)
$result = json_decode($array,true);
print_r($result['second']['second_b']); //輸出GOOD NIGHT
?>