强制在PHP中将数组添加到JSON的单个元素中 [英] Force to add array into single element of JSON in PHP

查看:95
本文介绍了强制在PHP中将数组添加到JSON的单个元素中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在自定义WordPress插件以导出JSON文件供第三方使用.

I'm customizing a WordPress plugin to export a JSON file for 3rd party use.

我需要在"order_item"中添加一个仅包含一项的数组.对于多个订单商品,将自动添加数组(方括号).

I need to add an array to "order_item" where it contain only one item. For the multiple order items, the array (square brackets) is automatically added.

我尝试了其他方法来将数组包含在$ child-> addChild('order_item')中,例如(array)$ child-> addChild('order_item'),但这应该是错误的方法.

I try different methods to include array to $child->addChild( 'order_item' ), for example (array)$child->addChild( 'order_item' ) but it should be wrong method.

生成json输出的函数如下:

a function to generate the json output is as follow:

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;
}   

这是我从输出中得到的:

This is what i get from the 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"
            }
        }
    ]
}

我希望在post_item中将该数组包括在postid中:12082

What i expected to include the array in order_item for 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"
                }
            ]
        }
    ]
}

推荐答案

这似乎是您在生成XML(使用SimpleXML)而不是JSON.我想象您使用json_encode()将SimpleXML对象的debug/vardump输出编译为JSON.

That looks like you're generating XML (using SimpleXML) not JSON. I imagine you use json_encode() to compile the debug/vardump output of the SimpleXML object to JSON.

此时,SimpleXML无法知道单个元素可能具有同级.

At this point SimpleXML can not know that the single element can potentially have siblings.

我建议您直接为JSON生成结构.使用PHP很简单.这是一个简化的示例(没有数据获取和过滤):

I suggest you generate the structure for the JSON directly. It is simple with PHP. Here is a reduced example (without data fetch and filter):

// simplified demo data
$orders = [
  '12081' => [
      'SAM1222' => 3,
      'NOK8777' => 3
  ], 
  '12082' => [
      'SON7411' => 1
  ]   
];

// associative arrays get encoded as objects in JSON
$result = [
  "transaction_date" => date('Ymd'),
  "neworders" => []    
];
foreach($orders as $orderId => $order) {
   $post = [
      'postid' => $orderId,
      'order_item' => []
   ];
   foreach ($order as $itemId => $quantity) {
       // numerical arrays will be encoded as arrays in JSON
       $post['order_item'][] = [
           "ugs" => $itemId,
           "qty" => $quantity
       ];
   }
   $result['neworders'][] = $post;
}
echo json_encode($result, JSON_PRETTY_PRINT);

输出:

{ 
  "transaction_date": "20190608", 
  "neworders": [ 
    { 
      "postid": 12081, 
      "order_item": [ 
        { 
          "ugs": "SAM1222", 
          "qty": 3 
        }, 
        {
          "ugs": "NOK8777",
          "qty": 3 
        } 
      ] 
    }, 
    { 
      "postid": 12082, 
      "order_item": [ 
        { 
          "ugs": "SON7411",
          "qty": 1 
        } 
      ] 
    } 
  ] 
}

这篇关于强制在PHP中将数组添加到JSON的单个元素中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆