views:

509

answers:

2

What's the fastest (best performing) way in PHP to transform a (My)SQL result like:

array(
 array('user_name' => 'john', 'tag_id' => 1, 'tag_name' => 'foo'),
 array('user_name' => 'john', 'tag_id' => 2, 'tag_name' => 'bar'),
 array('user_name' => 'rick', 'tag_id' => 3, 'tag_name' => 'foobar'),
 array('user_name' => 'rick', 'tag_id' => 2, 'tag_name' => 'bar')
);

Into the easier to use:

array(
 array('name' => 'john', 'tags' => array(
  array('id' => 1, 'name' => 'foo'),
  array('id' => 2, 'name' => 'bar')
 ),
 array('name' => 'rick', 'tags' => array(
  array('id' => 3, 'name' => 'foobar'),
  array('id' => 2, 'name' => 'bar')
 )
);

Or is there a library that does this already, without the added inflexibility and performance hit of full ORM?

Thanks

+2  A: 

Try this:

$data = array(
    array('user_name' => 'john', 'tag_id' => 1, 'tag_name' => 'foo'),
    array('user_name' => 'john', 'tag_id' => 2, 'tag_name' => 'bar'),
    array('user_name' => 'rick', 'tag_id' => 3, 'tag_name' => 'foobar'),
    array('user_name' => 'rick', 'tag_id' => 2, 'tag_name' => 'bar')
);
$final = array();
foreach ($data as $item) {
    if (!isset($final[$item['user_name']])) {
     $final[$item['user_name']] = array(
      'name' => $item['user_name'],
      'tags' => array()
     );
    }
    $final[$item['user_name']]['tags'][] = array(
     'id'   => $item['tag_id'],
     'name' => $item['tag_name']
    );
}
$final = array_values($final);
Gumbo
Ahh, you beat me to it.
Pim Jager
That wouldn't filter out duplicates. Of course, the query should do that but I would always double check. (And possibly log a warning on duplicates)
epochwolf
A: 

ezSQL at http://www.woyano.com/jv/ezsql should do what you want. I've taken over a project that uses it and it appear quite nicely put together. Myself I prefer to be somewhat closer to the metal, but if you wish to abstract away then it appears pretty solid in my experience.

Cruachan