php - How to deal with multiple Fields like Telephone Numbers in mySQL -
i think classical sql problem not able find hint on internet.
my database tables are:
table user: id username adress 1 uwe no 1 2 user2 no 2 3 name3 no 3 table tel: id telnumber user_id 1 123 1 2 234 1 3 123 2 4 567 1 5 900 3 6 800 3 7 111 1
with select:
select user.username, tel.telnumber, user.adress [user] inner join tel on user.id = tel.user_id;
i get:
username tel adress --------------------------- uwe 123 no 1 uwe 234 no 1 user2 123 no 2 uwe 567 no 1 name3 900 no 3 name3 800 no 3 uwe 111 no 1 ----------------------------
what i'am looking now:
name: uwe tel1: 123 tel2: 234 tel3: 567 tel4: 111 adress: no 1 name: name3 tel1: 900 tel2: 800 adress: no 3
how can result? how have adapt sql statement, comfortable way catch php?
you can use group_concat
group by
each user phone numbers. use explode, or other function split out phone numbers , iterate on them. example:
select u.username, group_concat(t.telnumber) numbers, u.adress user u inner join tel t on u.id = t.user_id group u.id
sql demo: http://sqlfiddle.com/#!9/6dca9b/3
php implementation like:
<?php $numers = array('user1' => '1', 'user2' => '123,456'); foreach($numers $user => $num){ echo $user . php_eol; if(strpos($num, ',') === false) { echo 'tel1:' . $num .php_eol; } else { $nums = explode(',', $num); foreach($nums $key => $temp){ echo 'tel' . ($key + 1) . ':' . $temp .php_eol; } } }
demo: https://3v4l.org/oe3ia
Comments
Post a Comment