【发布时间】:2019-06-08 06:53:28
【问题描述】:
我正在自定义一个 WordPress 插件以导出 JSON 文件以供第 3 方使用。
我需要将一个数组添加到“order_item”,它只包含一个项目。对于多个订单项目,自动添加数组(方括号)。
我尝试了不同的方法来将数组包含到 $child->addChild('order_item') 中,例如 (array)$child->addChild('order_item') 但它应该是错误的方法。
生成json输出的函数如下:
function woo_ce_export_dataset_override_order( $output = null ) {
global $export;
if( !empty( $export->fields ) ) {
$child = $output->addChild( 'transaction_date', date("Ymd", time()) );
foreach( $orders as $order ) {
$child = $output->addChild( apply_filters( 'woo_ce_export_xml_order_node', 'neworders' ) );
$args = $export->args;
$order = woo_ce_get_order_data( $order, 'order', $args, array_keys( $export->fields ) );
foreach( array_keys( $export->fields ) as $key => $field ) {
if( isset( $order->$field ) && isset( $export->columns[$key] ) ) {
if( !is_array( $field ) ) {
$child->addChild( apply_filters( 'woo_ce_export_xml_order_label', sanitize_key( $export->columns[$key] ), $export->columns[$key] ), esc_html( woo_ce_sanitize_xml_string( $order->$field ) ) );
}
}
}
if( !empty( $order->order_items ) ) {
foreach( $order->order_items as $order_item ) {
$order_item_child = $child->addChild( 'order_item' );
foreach( array_keys( $export->fields ) as $key => $field ) {
if( isset( $order_item->$field ) && isset( $export->columns[$key] ) ) {
if( !is_array( $field ) ) {
$order_item_child->addChild( apply_filters( 'woo_ce_export_xml_order_label', sanitize_key( $export->columns[$key] ), $export->columns[$key] ), esc_html( woo_ce_sanitize_xml_string( $order_item->$field ) ) );
}
}
}
}
}
}
// Allow Plugin/Theme authors to add support for sorting Orders
$output = apply_filters( 'woo_ce_orders_output', $output, $orders );
}
return $output;
}
这是我从输出中得到的:
{
"transaction_date": "20190607",
"neworders": [
{
"postid": "12081",
"order_item": [
{
"ugs": "SAM1222",
"qty": "3"
},
{
"ugs": "NOK8777",
"qty": "3"
}
]
},
{
"postid": "12082",
"order_item": {
"ugs": "SON7411",
"qty": "1"
}
}
]
}
我希望在 order_item 中包含 postid 的数组:12082
{
"transaction_date": "20190607",
"neworders": [
{
"postid": "12081",
"order_item": [
{
"ugs": "SAM1222",
"qty": "3"
},
{
"ugs": "NOK8777",
"qty": "3"
}
]
},
{
"postid": "12082",
"order_item": [
{
"ugs": "SON7411",
"qty": "1"
}
]
}
]
}
【问题讨论】: