[英]How to save PHP array in database by converting array into JSON?
这是我的 PHP 数组。 我想将其转换为 JSON。 转换为 JSON 后。 比在我想将它保存在数据库中之后我怎样才能做到这一点?
Array
(
[0] => 6:30pm
[1] =>
)
Array
(
[0] => 8:00pm
[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)
}
如果你真的需要将 json 存储在数据库中,你可以使用json_encode
和json_decode
。
使用这个json_encode($array)
,它会给你一个 json 字符串,你可以将它保存到一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.