【PHP函數】json_decode() ---- 對 JSON 格式的字符串進行解碼


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}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM