简体   繁体   中英

Loop through every value of string

I get form db field ( organisations.paths )the following strings:

/1/2/3/4

Each number is the id of organisation's name from this db table:

+----+-------------+----------+----------+----------------------+
| id | frameworkid |   path   | parentid |       fullname       |
+----+-------------+----------+----------+----------------------+
|  1 |           1 | /1       |        0 | NYC University       |
|  2 |           1 | /2       |        0 | Board of directors   |
|  3 |           1 | /1/2/3   |        1 | Math faculty         |
|  4 |           1 | /1/2/3/4 |        3 | Statistic department |
|  5 |           1 | /1/2/3/5 |        2 | Linguist  department |
+----+-------------+----------+----------+----------------------+

Then I have the description table for each organisation:

+----+----------+---------+----------------+
| id |   data   | fieldid | organisationid |
+----+----------+---------+----------------+
|  1 | HQ       |       1 |              1 |
|  2 | advisory |       1 |              2 |
|  3 | advisory |       1 |              3 |
|  4 | bottom   |       1 |              4 |
|  5 | advisory |       1 |              5 |
+----+----------+---------+----------------+

How to join the both description table and main table and loop only through organisations, which have HQ or advisory in their description? So it becomes:

NYC University, Board of directors, Math faculty (Statistic department-won't be shown, as it is with description bottom )

You need to use explode , IN and join Function of PHP and mysql.

$var = "/1/2/3/4";

$in = join(" , ", explode("/", ltrim($var, '/')));

$sql = "SELECT `dt`.`fullname` FROM `db_table` dt
        LEFT JOIN `organization` o
        ON `o`.`organisationid` = `dt`.`id`
        WHERE `o`.`id` IN ($in) AND (`o`.`data` = 'HQ' OR `o`.`data` = 'advisory')";

Make a loop to get the names and show them as you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM