douhao3562
2016-10-04 13:04
浏览 226

如何通过将数组转换为JSON来保存数据库中的PHP数组?

Here is a my PHP array. I want to convert it into JSON. after a converting to JSON. than after I want to save it in database how can I achieve this?

Array
(
    [0] => 6:30pm
    [1] => 
)
Array
(
    [0] => 8:00pm
    [1] => 
)
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • drruhc4944 2016-10-04 13:06
    已采纳

    If you really need to store json in the database, you can use json_encode and json_decode.

    点赞 打赏 评论
  • doujian1954 2016-10-04 13:07

    use this the json_encode($array) and it will gives you a json string,than you can save it to a row.

    点赞 打赏 评论
  • dongqian7545 2016-10-04 13:07

    json_encode() - Returns the JSON representation of a value.

    Returns a string containing the JSON representation of value.

    A numerically indexed PHP array is translated to an array literal in the JSON string. A JSON_FORCE_OBJECT option can be used if you want the array to be output as an object instead:

    Example One:

    <?php
    $ar = array('apple', 'orange', 'banana', 'strawberry');
    echo json_encode($ar,JSON_FORCE_OBJECT); 
    ?>
    

    Output:

    {"0":"apple","1":"orange","2":"banana","3":"strawberry"} 
    

    Example Two:

    <?php
    $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
    echo json_encode($arr);
    ?>
    

    Output:

    {"a":1,"b":2,"c":3,"d":4,"e":5}
    

    After you need to fetch the data you need json_decode() and it follows as this.

    json_decode() — Decodes a JSON string

    Takes a JSON encoded string and converts it into a PHP variable.

    Returns the value encoded in json in appropriate PHP type. Values true, false and null are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.

    Example:

    <?php
    $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
    var_dump(json_decode($json));
    var_dump(json_decode($json, true));
    ?>
    

    Output:

    object(stdClass)#1 (5) {
        ["a"] => int(1)
        ["b"] => int(2)
        ["c"] => int(3)
        ["d"] => int(4)
        ["e"] => int(5)
    }
    
    array(5) {
        ["a"] => int(1)
        ["b"] => int(2)
        ["c"] => int(3)
        ["d"] => int(4)
        ["e"] => int(5)
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题