2

I'm trying to create associative array of objects from row result set with member id as the key, but getting some error.

addATravelog() is just a function of the class UserLogsAndSOS(), whose objects i want in array.

Here is what I tried:

class UserArraySet {

private $arrayOfUsers = array();    

function createArrayForTravelogs($result) {
    While($row = $result->next()) {
        if(array_key_exists($row['id'], $this->arrayOfUsers)) {
            $this->arrayOfUsers[$row['id']] = new UserLogsAndSOS();
        }
    $this->arrayOfUsers[$row['id']]->addATravelog($row['title'], $row['blog']); //line     72                                           
    }
}
}

On calling createArrayForTravelogs() from the object I got the following error Here is the error I got:

Notice: Undefined index: 1 in C:\xampp\htdocs\site\classes\userprofile.php on line 72

Fatal error: Call to a member function addATravelog() on a non-object in C:\xampp\htdocs\site\classes\userprofile.php on line 72

Can someone please let me know how to achieve this, I want something like this:

Array (

 [1] => objectUserLogsAndSOS1

 [5] => objectUserLogsAndSOS2
 ....
)

where key is the member id from $row. I also need to check if the key exists, then call a function of that particular object to add data to its member, if not then create an object and then call a function of that particular object to add data to its member.

Thanks

3 Answers 3

2

just read the error message: you only create UserLogsAndSOS if there is already an entry - otherwise you call addATravelog on null. maybe you forgot the "!" in your if clause?

Sign up to request clarification or add additional context in comments.

2 Comments

Oops! wasted whole day and googled it all day long.. Thanx Del
your welcome, please mark the question as resolved and have a nice day
1

Because the array stays empty.

You only create a new UserLogsAndSOS when there already is an element with the provided ID in the arrayOfUsers. The exact opposite of what you probably wanted.

You're probably missing a ! to reverse the array_key_exist result.

Comments

0
if(!array_key_exists($row['id'], $this->arrayOfUsers)) {
   $this->arrayOfUsers[$row['id']] = new UserLogsAndSOS();
}

You missed and '!' I think this is causing the error

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.