0

I'm working on a project, and part of that project requires that I convert some of my sql results into an array of class objects.

for convenience sake, i prefer to set my array keys to be the primary key of the sql row so i can access them quickly.

the way i'm doing it right now is to just remap every object to a new array and i set the key manually as $object->id. is there any way i can have pdo do this while fetching the initial array so i don't need to do what i'm doing.

1 Answer 1

1

Well, you could do:

array_map(
    'reset', 
    $stmt->fetchAll(
        PDO::FETCH_GROUP|PDO::FETCH_CLASS, 
        'className'
    )
);

But that may not be much prettier than what you're doing now. See also here and here.

Or maybe something involving PDO::FETCH_KEY_PAIR?

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

2 Comments

pretty isn't that big a deal for me, i'm just trying to find a solution that will have the best performance. i was thinking that copying the objects over to a new array would be a hit to my mem. I like your solution, I'll probably try implementing it. Thanks :)
I like that solution, but it doesn't carry the primary key into the class. Assuming the class has a field for the PK, the value will be NULL.

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.