I will be honest, I have just started learning objects and I am stuck.
I want to loop through an array of objects and display the name and description for each. But either nothing is displayed or it displays all the names first and then all the descriptions.
I am pulling the information from an API into the object:
// get tasks
foreach($tasksList->items as $task_details) {
$tasks_name[$task_details->id]=$task_details->name;
$tasks_desc[$task_details->id]=$task_details->description;
$tasks_details[$task_details->id]=$task_details->id;
$tasks_progress[$task_details->id]=$task_details->progress;
}
foreach($tasks_name as $taskid=>$my_task_name) {
echo "Task_Name: " . $my_task_name . "</br>";
$task_id = $task_details->id;
foreach($tasks_desc as $taskid1=>$my_task_desc) {
if($taskid==$task_details->id) {
echo "Task_Desc: " . $my_task_desc . "</br>";
}
}
}
Now what I don’t understand is: inside the first foreach loop it is like a while loop while i=0, it checks $tasks_name[0], then $tasks_name[1] and so on.
However, I am not sure how to figure out what the id is in the current loop it is on, so I can tell it to only print the description of the current loop and not display all of them.
To be honest I am copying this from another example, but I don’t quite understand it. I plan to study objects more, but this is holding me up on my current code:
foreach($tasks_desc as $taskid1=>$my_task_desc)
I understand it is looping through all the $tasks_desc and assigning the value to $my_task_desc but what is the signifigance of $taskid?
Sorry for the newbie questions. 🙂
This is poorly written. I would move on to another tutorial if it’s a tutorial. Either that or the line that
task_idis used was left out.Anyway,
tasks_nameis an array of tasks indexed by the ID. So the outer loop in the second block loops over the keys/values of that array (the ID is the key,taskid. It was assigned by$task_details->idin the first loop above).The second loop goes over all of the tasks again, but this time by description
task_descinstead of by name. It’s trying to find thetask_descwith an ID that matches the ID of thetask_namebefore (which would make it the same task).That’s unnecessary, though, because you could just store all of the entries (name, desc, etc.) in one array indexed by the ID instead of storing each in their own array:
(this is the first loop):
However, you don’t even need to do that, because you can just iterate over
tasksList->itemswhen you need to.