php - 并非所有序列化数据都在输出
问题描述
我正在尝试使用 Wordpress 中的函数将序列化数据输出到使用 WP All Export 的电子表格中。它已成功反序列化,但是在我需要的所需部分下缺少数据。
功能如下:
<?php
function data_deserialize($value){
$output = '';
$data = maybe_unserialize($value);
$data = $data[0];
foreach ($data as $key => $value){
$output .= $key.': '.$value.'
';
}
return $output;
}
?>
以下序列化数据作为 $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";}}}}
但是,函数的输出会导致电子表格中出现这种情况
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
如您所见,它缺少 tmcp_post_fields 下的数据,这实际上是我需要导出到电子表格的数据。
为了实现这一目标,我缺少什么?
非常感谢
解决方案
由于 的值tmcp_post_fields
本身就是一个数组,因此您不能成功地将其附加到一个字符串中。这就是为什么你得到Array
的价值。
您需要做的是在函数中添加一些额外的内容以$value
在循环中处理(如果它是一个数组)并将其转换为可以附加的字符串。通过将循环移动到一个单独的函数并使其递归(并对结果字符串中的一些额外格式进行小调整),我已经快速构建了一些您可能可以使用的东西。不过,您可能想要调整函数以以对您自己有用的方式获取输出。
修改后的代码:
<?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;
}
您提供的序列化数据的预期输出:
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
]
]
推荐阅读
- java - 如何将数据集字符串类型转换为行类型?
- spring - 使用 Firebase 的基于角色的 API
- c# - 为什么我在 Unity 中的 3D 文本游戏对象变得清晰而不是改变颜色?
- c# - C# 复杂类构造从 JSON 读取/设置值
- c# - Unity2D 粒子系统 - 随机化层或 Z 变换值,用于与其他游戏对象出现在前面/后面/同一层
- geolocation - 从纬度/经度计算方位变化
- asp.net-core - 如何在 ASPNETCore 的抽象类中获取 HttpContext
- php - 使用“endroid/qr-code”库生成 qrcode 时未捕获的错误
- javascript - React Application 拥有一个暂存环境并在 AWS Elastic BeanStalk 上使用 Docker 进行部署
- ios - 使用 Vuejs 在 iOS 上安装 PWA 提示