douxieti6851 2019-06-08 06:53
浏览 267
已采纳

强制在PHP中将数组添加到JSON的单个元素中

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

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.

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.

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"
            }
        }
    ]
}

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"
                }
            ]
        }
    ]
}
  • 写回答

1条回答 默认 最新

  • doudao7511 2019-06-08 14:38
    关注

    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.

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

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

    Output:

    { 
      "transaction_date": "20190608", 
      "neworders": [ 
        { 
          "postid": 12081, 
          "order_item": [ 
            { 
              "ugs": "SAM1222", 
              "qty": 3 
            }, 
            {
              "ugs": "NOK8777",
              "qty": 3 
            } 
          ] 
        }, 
        { 
          "postid": 12082, 
          "order_item": [ 
            { 
              "ugs": "SON7411",
              "qty": 1 
            } 
          ] 
        } 
      ] 
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘