尝试将数组添加到关联数组

Trying to add an array to an associated array

我在我的数据库中保存了一个关联数组,我使用 Wordpress 函数 get_post_meta.

将其保存到一个名为 response_cost 的变量中
$response_cost = get_post_meta( $postID, $metaKey, true );

数组看起来像这样:

a:2: {
    i:0;a:3:
        {s:4:"type";s:6:"months";s:4:"cost";s:0:"";s:8:"modifier";s:1:"=";}
    i:1;a:3:
        {s:4:"type";s:5:"weeks";s:4:"cost";s:0:"";s:8:"modifier";s:1:"+";}
}

我创建了一个表单,它输出一个新数组并将其保存在一个名为 $add_to_response_cost.

的变量中
$add_to_response_cost = array (
    'type' => $type,
    'cost' => $cost,
    'modifyer' => $modifyer
);

我不知道如何添加 $add_to_response_cost 作为 $response_cost 的另一个实例,以便输出最终像这样:

a:3: {
    i:0;a:3:
        {s:4:"type";s:6:"months";s:4:"cost";s:0:"";s:8:"modifier";s:1:"=";}
    i:1;a:3:
        {s:4:"type";s:5:"weeks";s:4:"cost";s:0:"";s:8:"modifier";s:1:"+";}
    i:2;a:3:
        { my new array I've constructed via $add_to_response_cost }
}

非常感谢任何帮助或指导。

你可以试试 unserialize() 把它转换成数组。

$result = 反序列化($response_cost);

Print_r($结果);

要理解这个问题,首先我们需要解释一下在自定义字段中保存数组的工作原理

这里我们有一个数组

$array = array(
     "0" => array(
       "type" => "months",
       "cost" => null,
       "modifier" => "=",
     ),
     "1" => array(
      "type" => "weeks",
      "cost" => null,
      "modifier" => "+",
)
);

如果我们决定将其保存为数据库中的自定义字段,我们使用 update_post_meta() 函数

update_post_meta( 1, 'response_cost', $array );

在保存到数据库之前,Wordpress会serialize我们的数组,然后将其放入数据库。

因此,数组将按以下格式保存在数据库中

a:2:{i:0;a:3:{s:4:"type";s:6:"months";s:4:"cost";N;s:8:"modifier";s:1:"=";}i:1;a:3:{s:4:"type";s:5:"weeks";s:4:"cost";N;s:8:"modifier";s:1:"+";}}

然后,如果我们想得到一个数组,我们使用get_post_meta()

$myarray = get_post_meta(1, "response_cost", true); 

Wordpress 将从数据库中获取序列化数组并将其转换为典型数组。

然后我们可以将我们想要的任何数据添加到数组中并将其保存回数据库。

$add_to_response_cost = array (
    'type' => $type,
    'cost' => $cost,
    'modifyer' => $modifyer
);

$myarray[] = $add_to_response_cost;

update_post_meta( 1, 'response_cost', $myarray );

一般在使用get_post_meta函数时出现这个问题,没有指定key,只有一个参数(ID),那么我们得到的数组没有处理,必须先是unserialized

当您不是通过 Wordpress 函数而是通过直接 SQL 查询数据库从数据库中获取数组时,也会发生这种情况。 然后你需要先反序列化数组,向其中添加数据并打包回去。