【问题标题】:How to assign array to array variable which is store in a database如何将数组分配给存储在数据库中的数组变量
【发布时间】:2016-01-29 06:36:54
【问题描述】:

我将数组结构存储在数据库表中。

示例

table name - example
id=1
data= array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43")

我想从表中获取该数组结构并将数据列分配给一个数组。

例子

while($row=mysqli_fetch_array($result))
{
    $table=$row['data'];
}

我这样做了..但它不起作用。 结果是:

$table[0]=>array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43")

【问题讨论】:

  • $table[YOUR_ID_HERE] = YOUR_DATA;
  • $table=$row['data'][0];

标签: php arrays database


【解决方案1】:

您可以通过多种方式将数组数据保存到数据库字段。

我建议两种方式:

1) 序列化数组:

您可以使用 serialize() 函数保存数据。

e.g. $arr = array('234' => 'asfdads', 'asdf' => 'asdf2');
$toDb = addslashes(serialize($arr));

And then you can unserialize() them to get it back like:

$toDb = unserialize(stripslashes($fromDb));

2)使用json_encode()和json_decode();

e.g. $arr = array('234' => 'asfdads', 'asdf' => 'asdf2');
$toDb = json_encode($arr);

And then you can json_decode() them to get it back like:

$toDb = json_decode($fromDb)

【讨论】:

    猜你喜欢
    • 2022-11-23
    • 1970-01-01
    • 2018-02-08
    • 2016-12-12
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    相关资源
    最近更新 更多