json_decode() --- 對 JSON 格式的字符串進行解碼
1、用法:
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
參數說明:
-
$json: json格式的字符串
-
$assoc:
- 值為
true
: 表示返回數組
形式的數據 - 值為
false
:表示返回對象
形式的數據 - 默認為
false
- 值為
-
$depth:指定遞歸深度。
-
$options: JSON解碼的掩碼選項。 現在有兩個支持的選項。
- 第一個是
JSON_BIGINT_AS_STRING
, 用於將大整數轉為字符串
而非默認的float類型。 - 第二個是
JSON_OBJECT_AS_ARRAY
, 與將assoc設置為 TRUE 有相同的效果。
- 第一個是
2、范例:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'
-
json_decode($json);
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
} -
json_decode($json, true);
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
3、應用場景:
有返回的數據$modeofpayment
,需要對其進行循環輸出每條數據。如何實現?
其中:$modeofpayment
= [{"id":1,"name":"貨到付款"},{"id":2,"name":"支付寶付款"},{"id":3,"name":"微信付款"}]
;
(1)var_dump()打印結果為string '[{"id":1,"name":"貨到付款"},{"id":2,"name":"支付寶付款"},{"id":3,"name":"微信付款"}]'
其數據類型為string
(2)將數據轉化為數組形式:json_decode($json, true)
。得到結果為:
array (size=3)
0 =>
array (size=2)
'id' => int 1
'name' => string '貨到付款' (length=12)
1 =>
array (size=2)
'id' => int 2
'name' => string '支付寶付款' (length=15)
2 =>
array (size=2)
'id' => int 3
'name' => string '微信付款' (length=12)
(3)使用模板引擎循環輸出
{foreach name="$offer.modeofpayment" item="vo"}
<label class="iconfont wx">
<input type="radio" name="paymentmode" value="{$vo.id}" /> {$vo.name}
</label>
{/foreach}
或者
{volist name="$offer.modeofpayment" id="vo"}
<label class="iconfont wx">
<input type="radio" name="paymentmode" value="{$vo.id}" /> {$vo.name}
</label>
{/volist}