将关联的POST数据输入转换为序列化数组

时间:2011-07-25 21:28:51

标签: php serialization

我在表单中使用多维数组,我想将这些值解析为序列化数组,以存储在我的数据库中。这是我的HTML表单的相关部分:

<select name="week_days[monday]"><option value=""></option><option value="preferred">Preferred</option><option value="restricted">Restricted</option></select>
<select name="week_days[tuesday]"><option value=""></option><option value="preferred">Preferred</option><option value="restricted">Restricted</option></select>
<select name="week_days[wednesday]"><option value=""></option><option value="preferred">Preferred</option><option value="restricted">Restricted</option></select>
<select name="week_days[thursday]"><option value=""></option><option value="preferred">Preferred</option><option value="restricted">Restricted</option></select>

我想在我的模型中创建一个名为week_days的数组。我希望数组看起来像的一个例子是:

array('monday'=>'preferred','tuesday'=>'','wednesday'=>'restricted','thursday'=>'');

然后我将序列化()此数组以存储在我的数据库中。如何将多维数组输入转换为数组以进行序列化?

3 个答案:

答案 0 :(得分:5)

当您在表单中提交此内容时,您的$_POST['week_days']将与问题中的数组相同

答案 1 :(得分:3)

以下是一些示例代码:

<pre><?php

if ($_POST['week_days']) {
    print_r($_POST);
    print_r(serialize($_POST['week_days']));
}

?></pre>
<form method="post">
<select name="week_days[monday]"><option value=""></option><option value="preferred">Preferred</option><option value="restricted">Restricted</option></select>
<select name="week_days[tuesday]"><option value=""></option><option value="preferred">Preferred</option><option value="restricted">Restricted</option></select>
<select name="week_days[wednesday]"><option value=""></option><option value="preferred">Preferred</option><option value="restricted">Restricted</option></select>
<select name="week_days[thursday]"><option value=""></option><option value="preferred">Preferred</option><option value="restricted">Restricted</option></select>
<input type="submit"/>
</form>

哪些输出(基于所选内容):

Array
(
    [week_days] => Array
        (
            [monday] => preferred
            [tuesday] => restricted
            [wednesday] => restricted
            [thursday] => preferred
        )

)
a:4:{s:6:"monday";s:9:"preferred";s:7:"tuesday";s:10:"restricted";s:9:"wednesday";s:10:"restricted";s:8:"thursday";s:9:"preferred";}

答案 2 :(得分:2)

嗯......如果我理解正确的话,真的很直白:

$serialized = serialize ( $_POST['week_days'] );

会做你想做的......

那说了几句话:

  • 您可能想要创建一个新表来存储日期,并为首选项设置一个布尔列
  • 这不是一个多维数组,而是一个关联数组=)