最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

woocommerce offtopic - Unable to enocde the result of wc_get_products

matteradmin6PV0评论

I am using the following code to get the best selling products and send the result in JSON. But I am unable to encode the result of wc_get_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 );

I am using the following code to get the best selling products and send the result in JSON. But I am unable to encode the result of wc_get_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 );
Share Improve this question asked Nov 27, 2018 at 9:34 Sagar Bahadur TamangSagar Bahadur Tamang 1331 silver badge10 bronze badges
Add a comment  | 

1 Answer 1

Reset to default -1

Try:

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

OR

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

Encode array not object, wc_get_products will return object.

Post a comment

comment list (0)

  1. No comments so far