I have an associated array saved in my database that Im saving to a variable called response_cost
using the WordPress function get_post_meta
.
$response_cost = get_post_meta( $postID, $metaKey, true );
The array looks something like this:
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:"+";}
}
I have a form that I’ve created which outputs a new array and it’s saved in a variable called $add_to_response_cost
.
$add_to_response_cost = array (
'type' => $type,
'cost' => $cost,
'modifyer' => $modifyer
);
I’m can’t figure out how to add $add_to_response_cost
as another instance of $response_cost
so that the out put ends up like so:
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 }
}
Any help or direction with this is greatly appreciated.
2
Answers
You can try unserialize() to convert it to array.
$result = unserialize($response_cost);
Print_r($result);
To understand the problem, first we need to explain a little about how saving arrays in custom fields works
Here we have an array
If we decide to save it as a custom field in the database, we use the update_post_meta() function
Before saving it to the database, WordPress will serialize our array and then put it into the database.
As a result, the array will be saved in the database in the following format
Then, if we want to get an array, we use get_post_meta()
WordPress will take a serialized array from the database and convert it to a typical array.
Then we can add any data we want to the array and save it back to the database.
Usually this problem occurs when using the get_post_meta function without specifying a key, with only one parameter (ID), then we get arrays without processing and they must first be unserialized
This can also happen when you get an array from a database not through a WordPress function, but by direct SQL query to the database.
Then you need to unserialize the array first, add data to it and pack it back.