在一个字段中存储多个值

时间:2011-08-12 20:05:21

标签: php mysql arrays

我有一个脚本,它会在我的数据库中的单元格中插入一个值。该单元格将包含4个值。它应该如下所示:0; 0; 0; 0(每个'0',表示一个值)

如何在'0'数字3所在的位置插入示例值100,所以它看起来像这样:

0; 0; 100; 0

提前致谢。

3 个答案:

答案 0 :(得分:2)

这是糟糕的数据库设计,打破了数据库设计的first normal form

我建议您重新考虑您的架构和数据架构。

可能会将它们分解为各个列。

您的数据应按关系设计,以尽量减少列中的重复模式(请参阅上面的链接)

我几乎可以向你保证 更好的方式...

答案 1 :(得分:1)

查看serialize()unserialize()

$array = array(0,20,103,330);
$string = serialize($array); // store this in db

然后从db:

获取字符串
$array = unserialize($string);

使用数组访问/更新值并在db

中重新存储

或者如果您遇到以下格式:

$string = '0;0;100;0'; // coming from db
$array = explode(';' , $string);
$array[2] = 100;
$string = implode(';' , $array);

答案 2 :(得分:0)

<?php

    // original string of values seperated by colon
    $string = "0;0;0;0";

    // create array of values by splitting at colons
    $vals = preg_split('/;/', $string);

    // modify the value of any elements in your array
    $vals[2] = 100;

    // glue your array of values together with semicolons at the joins
    $string = implode(';',$vals);

    // check the value has been changed coreectly
    echo $string;

?>
相关问题