I am trying to use a function in Wordpress to output serialised data into a spreadsheet using WP All Export. It is successfully unserialising it, however it is missing data under the required section I need.
The function is as follows:
<?php
function data_deserialize($value){
$output = '';
$data = maybe_unserialize($value);
$data = $data[0];
foreach ($data as $key => $value){
$output .= $key.': '.$value.'
';
}
return $output;
}
?>
The following serialised data is being outputted as $value.
a:1:{i:0;a:9:{s:16:"tmcp_post_fields";a:2:{s:12:"tmcp_radio_0";s:11:"Test Card_9";s:15:"tmcp_textarea_1";s:19:"This is the message";}s:10:"product_id";i:934;s:19:"per_product_pricing";b:1;s:17:"cpf_product_price";s:2:"15";s:12:"variation_id";s:4:"1030";s:11:"form_prefix";s:0:"";s:20:"tc_added_in_currency";s:3:"GBP";s:19:"tc_default_currency";s:3:"GBP";s:14:"tmcartepo_data";a:2:{i:0;a:2:{s:3:"key";s:11:"Test Card_9";s:9:"attribute";s:12:"tmcp_radio_0";}i:1;a:2:{s:3:"key";s:19:"This is the message";s:9:"attribute";s:15:"tmcp_textarea_1";}}}}
However the output of the function results in this within the spreadsheet
tmcp_post_fields: Array
product_id: 934
per_product_pricing: 1
cpf_product_price: 15
variation_id: 1030
form_prefix:
tc_added_in_currency: GBP
tc_default_currency: GBP
tmcartepo_data: Array
As you can see, it is missing the data under tmcp_post_fields which is actually the data I need exported to the spreadsheet.
What am I missing to achieve this?
Many thanks
Since the value of tmcp_post_fields
is an array itself, you can't successfully just append it to a string. That's why you're getting Array
as the value.
What you'll need to do is add something extra to your function to handle $value
in the loop if it's an array and turn it into a string that you can append. I've quickly spun up something you might be able to use, by moving your loop into a separate function and making it recursive (and a small tweak for a bit of extra formatting in the resulting string). You might want to tweak the function to get the output in a way that's useful for yourself though.
Revised code:
<?php
function data_deserialize($value) {
$data = maybe_unserialize($value);
$data = $data[0];
return array_to_string($data);
}
function array_to_string($data, $indent = '') {
$output = '';
foreach ($data as $key => $value) {
if (is_array($value)) {
$value = array_to_string($value, "{$indent}\t");
$value = "[\n{$value}{$indent}]";
}
$output .= "{$indent}{$key}: {$value}\n";
}
return $output;
}
Expected output from the serialized data you provided:
tmcp_post_fields: [
tmcp_radio_0: Test Card_9
tmcp_textarea_1: This is the message
]
product_id: 934
per_product_pricing: 1
cpf_product_price: 15
variation_id: 1030
form_prefix:
tc_added_in_currency: GBP
tc_default_currency: GBP
tmcartepo_data: [
0: [
key: Test Card_9
attribute: tmcp_radio_0
]
1: [
key: This is the message
attribute: tmcp_textarea_1
]
]