數組和json的相互轉換

來源:互聯網
上載者:User

標籤:blog   2014   ar   log   size   file   php   ef   

json_encode()

<?php/*****一維數組*********///有鍵$arr = array('a'=>1, 'b'=>2,'c'=>3,);$json = json_encode($arr);echo($json);  //{"a":1,"b":2,"c":3}//無鍵$arr = array(1,2,3);$json = json_encode($arr);echo($json);  //[1,2,3]/*****二維數組*********///有鍵$arr = array('a' => array('id'=>1, 'xuefei'=>"100" ), 'b' => array('id'=>2, 'xuefei'=>"200" ),'c' => array('id'=>3, 'xuefei'=>"300" ),);$json = json_encode($arr);echo($json);  //{"a":{"id":1,"xuefei":"100"},"b":{"id":2,"xuefei":"200"},"c":{"id":3,"xuefei":"300"}}//無鍵$arr = array(array('id'=>1, 'xuefei'=>"100" ), array('id'=>2, 'xuefei'=>"200" ),array('id'=>3, 'xuefei'=>"300" ),);$json = json_encode($arr);echo($json);  //[{"id":1,"xuefei":"100"},{"id":2,"xuefei":"200"},{"id":3,"xuefei":"300"}]?>

json_decode

<?php/*****一維json*********///有鍵$json = '{"a":1,"b":2,"c":3}'; //不加key的話輸出null$arr = json_decode($json);var_dump($arr);/*輸出:object(stdClass)[1]  public 'a' => int 1  public 'b' => int 2  public 'c' => int 3*/ //無鍵$json = '["a","b","c"]';  //加key的話輸出null$arr = json_decode($json);var_dump($arr);/*輸出:array (size=3)  0 => string 'a' (length=1)  1 => string 'b' (length=1)  2 => string 'c' (length=1)*//*****二維json*********///有鍵$json = '{"a":{"id":1,"xuefei":"100"},"b":{"id":2,"xuefei":"200"},"c":{"id":3,"xuefei":"300"}}';$arr = json_decode($json,true);var_dump($arr);/*輸出:array (size=3)  'a' =>     array (size=2)      'id' => int 1      'xuefei' => string '100' (length=3)  'b' =>     array (size=2)      'id' => int 2      'xuefei' => string '200' (length=3)  'c' =>     array (size=2)      'id' => int 3      'xuefei' => string '300' (length=3)*/ //無鍵$json = '[{"id":1,"xuefei":"100"},{"id":2,"xuefei":"200"},{"id":3,"xuefei":"300"}]';$arr = json_decode($json,true);var_dump($arr);/*輸出:array (size=3)  0 =>     array (size=2)      'id' => int 1      'xuefei' => string '100' (length=3)  1 =>     array (size=2)      'id' => int 2      'xuefei' => string '200' (length=3)  2 =>     array (size=2)      'id' => int 3      'xuefei' => string '300' (length=3)*/ ?>



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.