如何通过将数组转换为JSON将PHP数组保存在数据库中?
这是一个我的PHP数组。我想把它转换成JSON。在转换为JSON之后。在我想将其保存到数据库中之后,我如何才能实现这一点如何通过将数组转换为JSON将PHP数组保存在数据库中?,php,mysql,json,Php,Mysql,Json,这是一个我的PHP数组。我想把它转换成JSON。在转换为JSON之后。在我想将其保存到数据库中之后,我如何才能实现这一点 Array ( [0] => 6:30pm [1] => ) Array ( [0] => 8:00pm [1] => ) 如果你真的需要在数据库中存储json,你可以使用json\u encode和json\u decode使用这个json\u encode($array),它会给你一个json字符串,然后你可以
Array
(
[0] => 6:30pm
[1] =>
)
Array
(
[0] => 8:00pm
[1] =>
)
如果你真的需要在数据库中存储json,你可以使用
json\u encode
和json\u decode
使用这个json\u encode($array)
,它会给你一个json字符串,然后你可以将它保存到一行。json\u encode()
-返回一个值的json表示形式
返回包含值的JSON表示形式的字符串
数字索引的PHP数组被转换为JSON字符串中的数组文本。如果希望将数组作为对象输出,可以使用JSON\u FORCE\u 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}
<?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)
}
示例二:
<?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}
<?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\u decode()
,如下所示
json\u decode()
-解码json字符串
获取JSON编码的字符串并将其转换为PHP变量
返回用json编码的适当PHP类型的值。值true、false和null分别作为true、false和null返回。如果无法解码json或编码数据深度超过递归限制,则返回NULL
示例:
<?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}
<?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\u encode
他为什么不在数据库中存储json的可能副本?“一切都很好,但现在更有意义了:你在开玩笑,不是吗?@jakubwrona我为什么要开玩笑?