【问题标题】:How to save PHP array in database by converting array into JSON?如何通过将数组转换为 JSON 将 PHP 数组保存在数据库中?
【发布时间】:2016-10-04 13:04:37
【问题描述】:

这是我的 PHP 数组。我想把它转换成 JSON。转换为 JSON 后。比我想将它保存在数据库中之后如何实现这一点?

Array
(
    [0] => 6:30pm
    [1] => 
)
Array
(
    [0] => 8:00pm
    [1] => 
)

【问题讨论】:

标签: php mysql json


【解决方案1】:

json_encode() - 返回值的 JSON 表示形式。

返回一个包含值的 JSON 表示形式的字符串。

数字索引的 PHP 数组被转换为 JSON 字符串中的数组文字。如果您希望将数组作为对象输出,则可以使用 JSON_FORCE_OBJECT 选项:

示例一:

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

输出:

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

示例二:

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

输出:

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

在你需要获取数据之后,你需要json_decode(),如下所示。

json_decode() — 解码 JSON 字符串

采用 JSON 编码的字符串并将其转换为 PHP 变量。

以适当的 PHP 类型返回以 json 编码的值。值 true、false 和 null 分别返回为 TRUE、FALSE 和 NULL。如果无法解码 json 或编码的数据比递归限制深,则返回 NULL。

示例:

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

输出:

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)
}

【讨论】:

    【解决方案2】:

    如果确实需要在数据库中存储json,可以使用json_encode和json_decode。

    【讨论】:

    【解决方案3】:

    使用json_encode($array),它会给你一个json字符串,而不是你可以将它保存到一行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-22
      • 2014-11-25
      • 2012-09-15
      • 1970-01-01
      • 2018-05-15
      • 1970-01-01
      • 2017-09-09
      • 2018-02-17
      相关资源
      最近更新 更多