0

I faced with problem while fetching query results, my code:

$result = $query->execute();
$array1 = $result->fetchAllKeyed(1, 0);
$array2 = $result->fetchAllKeyed(2, 0);

But the $array2 is empty, so fetchAllKeyed cut all values from $result.

I'm already tried to use the following:

$query2 = clone $query;
$result = $query->execute();
$result2 = $query2->execute();
$array1 = $result->fetchAllKeyed(1, 0);
$array2 = $result2->fetchAllKeyed(2, 0);

It's works, but I don't want do two queries instead of one.

So, how can I do two (or more) different "fetch" from one result?

  • Did try duplicating the $result directly instead of recreating the query? $result2 = $result and then fetching the keys? – Suranga Panagamuwa Gamage May 30 '15 at 9:55
  • Doesn't works too. If I use $result2 = $result; - I get empty fetch result. If I use $result2 = clone $result; - the same. – kala4ek May 30 '15 at 12:30
  • Hmm, then I guess you'll have to use fetchAssoc() wich gets you an array of objects and then use a foreach loop to generate the 2 sub arrays. Seems like the only solution. – Suranga Panagamuwa Gamage May 30 '15 at 13:51
0

Since fetchAllKeyed() internally uses foreach loop to sort the data, the answer given by Suranga Panagamuwa Gamage to use fetchAssoc() and then a loop seems the most efficient way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.