I'm trying to pull out the values from an array with embedded objects and I can't figure out how to reference the items I need. I call a function (working in WordPress with LearnDash plugins) which returns an array. The call I use and the echo to see the structure is:
$my_lessons = learndash_get_course_lessons_list( $course_id, $user_id, $query_args );
echo "<pre>";
var_dump($my_lessons);
echo "</pre>";
It returns:
array(10) {
[1]=>
array(9) {
["sno"]=>
int(1)
["id"]=>
int(38155)
["post"]=>
object(WP_Post)#9918 (24) {
["ID"]=>
int(38155)
["post_author"]=>
string(1) "9"
["post_date"]=>
string(19) "2023-10-07 15:01:55"
["post_date_gmt"]=>
string(19) "2023-10-07 15:01:55"
["post_content"]=>
string(0) ""
["post_title"]=>
string(45) "Lesson 1: Happy Family, Healthy Brain (adult)"
["post_excerpt"]=>
string(0) ""
["post_status"]=>
string(7) "publish"
["comment_status"]=>
string(6) "closed"
["ping_status"]=>
string(6) "closed"
["post_password"]=>
string(0) ""
["post_name"]=>
string(41) "lesson-1-happy-family-healthy-brain-adult"
["to_ping"]=>
string(0) ""
["pinged"]=>
string(0) ""
["post_modified"]=>
string(19) "2023-10-07 15:01:57"
["post_modified_gmt"]=>
string(19) "2023-10-07 15:01:57"
["post_content_filtered"]=>
string(0) ""
["post_parent"]=>
int(0)
["guid"]=>
string(68) "https://xxx.xxx.com/?post_type=sfwd-lessons&p=38155"
["menu_order"]=>
int(1)
["post_type"]=>
string(12) "sfwd-lessons"
["post_mime_type"]=>
string(0) ""
["comment_count"]=>
string(1) "0"
["filter"]=>
string(3) "raw"
}
["permalink"]=>
string(121) "https://xxx.xxx.com/courses/sfp-finding-home-adult-english/lessons/lesson-1-happy-family-healthy-brain-adult/"
["class"]=>
string(0) ""
["status"]=>
string(9) "completed"
["sample"]=>
string(13) "is_not_sample"
["sub_title"]=>
string(0) ""
["lesson_access_from"]=>
string(0) ""
}
and so on for each lesson.
I want to be able to pull out the id (which is 38155) and the post_title from the object (Lesson 1: Happy Family, Healthy Brain (adult)) but I am confused on how to proceed. Any suggestions?
I tried looping though the array using
foreach ($my_lessons as $k => $v) {
$my_return .= "<br>".$k."<br>";
$my_return .= "<br>lesson: ".$v["id"]."<br>";
}
This gets me the ids, but then I am not sure how to get the post_title.
The array returned by learndash_get_course_lessons_list() includes an object, namely an instance of the Wordpress WP_Post object. You therefore have to use a combination of array and object syntax to access the variable you want.
The WP_Post object is in the ['post'] field of each row in your array. In this case $my_lessons[0]['post']->ID
and $my_lessons[0]['post']->post_title
are the full names of variables you need (without using a foreach loop).
You could output the ID and name something like this:
$my_return = '';
foreach ($my_lessons as $k => $v) {
$my_return .= "<br>Lesson name: " . $v["post"]->post_title . "<br>";
$my_return .= "<br>Lesson id: " . $v["post"]->ID. "<br>";
}
echo $my_return;