php - mysql fastest 2 table query -
situation: 2 tables, first (persons) storing person names , other data, , second (phones) storing phone numbers. there can multiple phone numbers per person (thats why using separate tables in first place).
goal: select in end i'd have php array this:
array ( '0' => array ( 'name' => 'john smith' // other values table persons... 'phones' => array('0' => '12345', '1' => '324343') // phones table ), '1' => array ( 'name' => 'adam smith' // other values table persons... 'phones' => array('0' => '645646', '1' => '304957389', '2' => '9435798') // phones table ) );
etc.
phones.person_id = persons.id
what fastest way this? fastest in sense of program execution time, not coding time. simple join in case i'd many duplicate rows, i.e. each phone data of same person again , again in each row if see mean. need work on array in php side. maybe there's better way?
one query. check typos:
$return = array(); $query = "select pe.id, pe.name, ph.phone persons pe inner join phones ph on pe.id = ph.person_id "; $results = mysql_query($query); if($results && mysql_num_rows($results)) { while($row = mysql_fetch_assoc($results)) { if(!$return[$row['id']]) { $return[$row['id']] = array('name' => $row['name'], 'phones' => array()); } array_push($return[$row['id']]['phones'], $row['phone']); } } return $return;
Comments
Post a Comment