Link to home
Start Free TrialLog in
Avatar of sittinDuck
sittinDuck

asked on

Slash between values question

Hello experts!

I have 10 columns in my database called table_nightclub_1, table_nightclub_2, table_nightclub_3, table_nightclub_4 and so on. Datatype = enum('Y', 'N', '').

Y if the table is booked - N if not.

How can I echo '1 / 2 / 3' if table 1, 2 and 3 are booked? And only '1' if table 1 is booked? '8 / 9' if table 8 and 9 are booked.

I can't find a smart way to make a slash between the values:-/ Hope someone can help me!

Thanks in advance!
Avatar of Richard Quadling
Richard Quadling
Flag of United Kingdom of Great Britain and Northern Ireland image

Try this. Uses closures and array functions.Outputs ...1 / 4 / 7 / 10
<?php
// Assuming data coming from database is in 1 row.
$data = array
	(
	'table_nightclub_1' => 'Y',
	'table_nightclub_2' => 'N',
	'table_nightclub_3' => 'N',
	'table_nightclub_4' => 'Y',
	'table_nightclub_5' => 'N',
	'table_nightclub_6' => 'N',
	'table_nightclub_7' => 'Y',
	'table_nightclub_8' => 'N',
	'table_nightclub_9' => 'N',
	'table_nightclub_10' => 'Y',
	);

echo
	implode // Step 4 : Implode them.
		(
		' / ',
		array_map // Step 3 : Drop the textual part of the keys.
			(
			function($value)
				{
				return substr($value, strlen('table_nightclub_'));
				},
			array_keys // Step 2 : Get the keys from the remaining 'Y's.
				(
				array_filter // Step 1 : Remove 'N's from array.
					(
					$data,
					function($value)
						{
						return 'N' != $value;
						}
					)
				)
			)
		);

Open in new window

Another option would be to do it in SQL ...


SELECT
      CASE WHEN table_nightclub_1 = 'Y' THEN '1 / ' ELSE '' END +
      CASE WHEN table_nightclub_2 = 'Y' THEN '2 / ' ELSE '' END +
      CASE WHEN table_nightclub_3 = 'Y' THEN '3 / ' ELSE '' END +
      CASE WHEN table_nightclub_4 = 'Y' THEN '4 / ' ELSE '' END +
      CASE WHEN table_nightclub_5 = 'Y' THEN '5 / ' ELSE '' END +
      CASE WHEN table_nightclub_6 = 'Y' THEN '6 / ' ELSE '' END +
      CASE WHEN table_nightclub_7 = 'Y' THEN '7 / ' ELSE '' END +
      CASE WHEN table_nightclub_8 = 'Y' THEN '8 / ' ELSE '' END +
      CASE WHEN table_nightclub_9 = 'Y' THEN '9 / ' ELSE '' END +
      CASE WHEN table_nightclub_10 = 'Y' THEN '10' ELSE '' END
            AS Booked
FROM
      table

and in PHP

$Booked = trim($data['Booked'], ' /');

sort of thing.
Avatar of sittinDuck
sittinDuck

ASKER

There was an error with the first solution

Parse error: syntax error, unexpected T_FUNCTION, expecting ')' in /home/tabelreservation.dk/wwwroot/test.php on line 23
ASKER CERTIFIED SOLUTION
Avatar of Richard Quadling
Richard Quadling
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
THANK you :-)

Just what I needed!