这个问题是基于现有的帖子 强制将数组添加到PHP中的JSON的单个元素中
现在我需要在第三方WordPress导出插件中添加一些自定义函数,以制作我想要的JSON输出。由于我对PHP和数组有一些有限的知识,所以希望得到你们的帮助
此代码仍需要修复两个问题:
1(order_item postid=32081无法显示所有项目(共3个订单项目(,目前只显示最后一个,例如ugs=A0003
2(需要在order_item下的所有参数中包含数组(或方括号(
用于导出 JSON 的现有函数
function woo_ce_export_dataset_override_order( $output = null, $export_type = null) {
global $export;
$orders = woo_ce_get_orders( 'order', $export->args );
if( !empty( $orders ) ) {
if( !empty( $export->fields ) ) {
$export->total_columns = $size = count( $export->columns );
$output = [
"transaction_date" => date('Ymd'),
"neworders" => []
];
if( !empty( $export->fields ) ) {
foreach( $orders as $order ) {
$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] ) ) {
$post[ $export->columns[$key] ] = $order->$field;
}
}
if( !empty( $order->order_items ) ) {
foreach( $order->order_items as $order_item ) {
foreach( array_keys( $export->fields ) as $key => $field ) {
if( isset( $order_item->$field ) && isset( $export->columns[$key] ) ) {
$post['order_item'][ $export->columns[$key] ] = $order_item->$field;
}
}
}
}
$output['neworders'][] = $post;
}
}
}
}
return array($output);
}
我从输出中得到什么
[
{
"transaction_date": "20190609",
"neworders": [
{
"postid": 32081,
"label": "22615",
"address": "19 RUE",
"postcode": "27450",
"order_item": {
"ugs": "A0003",
"qty": "6"
}
},
{
"postid": 32082,
"label": "22617",
"address": "2 impas",
"postcode": "12300",
"order_item": {
"ugs": "B0002",
"qty": "1"
}
}
]
}
]
我需要什么
[
{
"transaction_date": "20190609",
"neworders": [
{
"postid": 32081,
"label": "22615",
"address": "19 RUE",
"postcode": "27450",
"order_item": [
{
"ugs": "A0001",
"qty": "3"
},
{
"ugs": "A0002",
"qty": "1"
},
{
"ugs": "A0003",
"qty": "6"
}
]
},
{
"postid": 32082,
"label": "22617",
"address": "2 impas",
"postcode": "12300",
"order_item": [
{
"ugs": "B0001",
"qty": "1"
}
]
}
]
}
]
您的代码每次通过时都会覆盖 order_item
数组。这就是为什么只有最后一个出现。添加一个计数器以将所有项目添加为数组:
foreach( array_keys( $export->fields ) as $key => $field ) {
if( isset( $order_item->$field ) && isset( $export->columns[$key] ) ) {
$post['order_item'][$i][ $export->columns[$key] ] = $order_item->$field;
}
$i++;
}