无法编码wc_get_Products的结果

时间:2018-11-27 作者:Sagar Bahadur Tamang

我使用以下代码获得最畅销的产品,并以JSON格式发送结果。但我无法对wc\\u get\\u products()的结果进行编码。

    $best_selling_args = array(
        \'meta_key\' => \'total_sales\', 
        \'order\'    => \'DESC\',
        \'orderby\'  => \'meta_value_num\'
     );

    $products_posts = wc_get_products( $best_selling_args );

//  var_dump( $products_posts );

    echo wp_json_encode( $products_posts );

1 个回复
SO网友:Jaydip Nimavat

尝试:

$products_posts_arr = (array) $products_posts;
echo json_encode( $products_posts_arr );

function object_to_array($data) {
    if (is_array($data) || is_object($data)) {
        $result = array();
        foreach ($data as $key => $value) {
            $result[$key] = object_to_array($value);
        }
        return $result;
    }
    return $data;
}

$products_posts_arr = object_to_array( $products_posts );
echo json_encode( $products_posts_arr );
编码数组非对象,wc_get_products 将返回对象。

结束

相关推荐