Home > Software engineering >  Add extra fields to Array
Add extra fields to Array

Time:01-10

I have a funtion that gives me reviews for a given course ID.

$reviews

Now this return json response something like below.

[
    {
        "ID":463805,
        "post_author":"15387",
        "post_date":"2023-01-05 11:29:08",
        "post_date_gmt":"2023-01-05 10:29:08",
        "post_content":"xyz
    }
} 

I want to add extra field foreach review in this array. let say author_name.

How can I modify $reviews using foreach or something before the return.

function get_course_reviews( $data ) {
    global $reviews_query;
$sort_by = 'date';
    $review_args = array(
    'orderby'        => $sort_by,
);
    $course_ID = $data['id'];
   $reviews   = rrf_get_all_course_reviews( $course_ID, $review_args );
    return $reviews;
}

CodePudding user response:

You can use foreach loop to modify WP_Post object like below:

function get_course_reviews( $data ) {
    global $reviews_query;
    $sort_by = 'date';
        $review_args = array(
        'orderby'        => $sort_by,
    );
    $course_ID = $data['id'];
    $reviews   = rrf_get_all_course_reviews( $course_ID, $review_args );

    // Modify reviews object with custom field
    foreach($reviews as $review){
        $review->author_name = 'xyz';
    }

    return $reviews;
}

CodePudding user response:

You can use array_map

Assuming that you have converted your JSON to an array below can be an option.

E.g:

$updatedReviews = array_map(function ($review) {
 
  $review['author_name'] = 'any_name'; // TODO add your logic for the name here

  return $review;

}, $reviews);
  • Related