php 轉換 json 方法
阿新 • • 發佈:2018-11-10
說明
瞭解 PHP 下陣列使用方法
瞭解函式 json_decode, json_encode 使用方法
php 環境下如何輸出 json 格式
前提
PHP 下, 預設不支援直接進行 json 格式定義
PHP 下支援 array 定義
可以通過函式幫助, 把(多維)陣列轉換成為 json 格式輸出
注意, 中文字元需要特殊處理
陣列
一維陣列定義方法
定義方法
$a= [ 'a' => '123', 'b' => '234' ];
$b=array( 'a' => '123', 'b' => '234' );
print_r ($a);
print_r ($b);
輸出效果
Array
(
[a] => 123
[b] => 234
)
Array
(
[a] => 123
[b] => 234
)
多維陣列定義方法
定義方法,
$a = array(
'a' => '123',
'b' => array(
'c' => '234',
'd' => '345',
),
'e' => '456',
);
$b = [
'f' => '123',
'g' => [
'h' => '234',
'i' => '345',
],
'j' => '456',
];
輸出效果
Array
(
[a] => 123
[b] => Array
(
[c] => 234
[d] => 345
)
[e] => 456
)
Array
(
[f] => 123
[g] => Array
(
[h] => 234
[i] => 345
)
[j] => 456
)
陣列疊加方法
定義方法
$c = array();
array_push($c, $a);
array_push($c, $b);
print_r ($c);
輸出效果
Array
(
[0] => Array
(
[a] => 123
[b] => Array
(
[c] => 234
[d] => 345
)
[e] => 456
)
[1] => Array
(
[f] => 123
[g] => Array
(
[h] => 234
[i] => 345
)
[j] => 456
)
)
把陣列定義為 JSON 格式
定義方法: (注意,帶中文輸出)
$a = array(
'a' => '123',
'b' => array(
'c' => '234',
'd' => '345',
),
'e' => '中文字元456',
);
$b = [
'f' => '123',
'g' => [
'h' => '234',
'i' => '345',
],
'j' => '中文字元c',
];
$c = array();
array_push($c, $a);
array_push($c, $b);
var_dump(json_encode($c,JSON_UNESCAPED_UNICODE));
輸出效果
string(119) "[{"a":"123","b":{"c":"234","d":"345"},"e":"中文字元456"},{"f":"123","g":{"h":"234","i":"345"},"j":"中文字元c"}]"
參考例子
例子:
這裡有兩個多維陣列,陣列具有相同的元素 ‘uuid’
把陣列轉換為 JSON
定義方法
<?php
$a = [
'uuid' => 'c5966c24-7e8d-4e22-b4c8-29a035fec704',
'ipaddr' => '1.1.1.1',
'hostname' => 'test1.google.com',
];
$b = [
'uuid' => '3e7a74b4-75df-41b5-b0f9-88f459b68b3c',
'ipaddr' => '2.2.2.2',
'hostname' => 'test2.google.com',
];
$c = array();
array_push($c, $a);
array_push($c, $b);
$d = [
'uuid' => 'c5966c24-7e8d-4e22-b4c8-29a035fec704',
'user' => 'terry',
'sex' => 'male',
];
$e = [
'uuid' => '3e7a74b4-75df-41b5-b0f9-88f459b68b3c',
'user' => 'mary',
'sex' => 'female',
];
$f = array();
array_push($f, $d);
array_push($f, $e);
$g = json_encode($c,JSON_UNESCAPED_UNICODE);
$h = json_encode($f,JSON_UNESCAPED_UNICODE);
print $g;
print $h;
?>
輸出效果
json1
[{"uuid":"c5966c24-7e8d-4e22-b4c8-29a035fec704","ipaddr":"1.1.1.1","hostname":"test1.google.com"},{"uuid":"3e7a74b4-75df-41b5-b0f9-88f459b68b3c","ipaddr":"2.2.2.2","hostname":"test2.google.com"}]
json2
[{"uuid":"c5966c24-7e8d-4e22-b4c8-29a035fec704","user":"terry","sex":"male"},{"uuid":"3e7a74b4-75df-41b5-b0f9-88f459b68b3c","user":"mary","sex":"female"}]
把上述兩個陣列組合為一個數組
組合方法
foreach(json_decode($g, JSON_UNESCAPED_UNICODE) as $key => $array)
{
$r[$key] = array_merge(json_decode($h, JSON_UNESCAPED_UNICODE)[$key],$array);
}
輸出效果, 結合成為一個 json 資料
[{"uuid":"c5966c24-7e8d-4e22-b4c8-29a035fec704","user":"terry","sex":"male","ipaddr":"1.1.1.1","hostname":"test1.google.com"},{"uuid":"3e7a74b4-75df-41b5-b0f9-88f459b68b3c","user":"mary","sex":"female","ipaddr":"2.2.2.2","hostname":"test2.google.com"}]