0

I am working on a PHP application that is connected to a RESTful webservice which itself is connected to a Database. And in my RESTful I have an Enum that saves the Enum's values as integers in the databse. But when I have to make GET Api in the PHP layer, is there anyway that I can somehow convert, I don't know if that is the right word, the int values into string so that in stead of showing 2 it shows "Single" for example.

This is the Enum I have in the Webservice.

public enum BookingType { Single, Group, Tournament }

And this the php part.

<?php
$uri2 = "http://examdatabasebooking.cloudapp.net/BookingService.svc/getbookings/";
if (isset($_POST["DateAndTimeFrom"])) {
        $FDateAndTimeFrom = $_POST["DateAndTimeFrom"];

$jsondata = file_get_contents($uri2 . $FirstName);
$booking = json_decode($jsondata, TRUE);

Note: In the foreach I just tried something like extracting the BookingType as the value and then setting the value as an array which holds the Enum values, so everytime I GET a booking, depending on the enum value it will write out Single, Group or Tournament.. But it doesn't work..

foreach ($booking as $value) {
  $jsondata = $value["BookingType"];
  $value = array("Single" => 0, "Group" => 1, "Tournament" => 2);
}
if(empty($booking)) {
 echo "No bookings!";
else {    
echo $booking["DateAndTimeFrom"] . " " . $booking["DateAndTimeTo"] . " " .     $booking["BookingType"];     
}

}
?>

And this is what it prints out: DateAndTimeFrom: Oct 5 2016 1:00PM DateAndTimeTo: Oct 5 2016 2:00PM BookingType: 2 <= this should print out Tournament in stead of 2

1
  • Or create them as "Backed Cases" - "have an additional read-only property, value, which is the value specified in the definition." then $enumCase->value or YourEnum::YourCase->value php.net/manual/en/language.enumerations.backed.php Commented Mar 3, 2022 at 10:28

1 Answer 1

1

You could declare an array for your values.

$bookingTypes = array(
    'Single',
    'Group',
    'Tournament'
);

And to get the string, with your $booking['bookingType']:

echo $bookingTypes[$booking['bookingType']]; // Tournament

And if you have custom values instead of 0, 1 and 2:

$bookingTypes = array(
    9 => 'Single',
    20 => 'Group',
    54 => 'Tournament'
);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.