douhezi2285 2019-01-25 20:19
浏览 28
已采纳

php使用0键作为URL中的值来检索数据

So recently I was working on fixing an older system which is using keys from an array to retrieve certain data.

This is the array with several brands of cars, the key is used to filter certain things so the URL would look like http://example.com/page?brands=1&foo=bar

public static $carBrandGroups = [
    0 => 'Volvo',
    1 => 'BMW',
    2 => 'Renault',
    3 => 'Tesla',
    4 => 'Opel',
    5 => 'Peugeot',
    6 => 'Toyota',
    7 => 'Mercedes',
    8 => 'Honda',
    9 => 'Fiat',
]

Now the system works and retrieves everything except when 0 is passed which is logical since 0 is considered empty. I believe there must be a way, is there?

The function which passes additional information is shown below:

public static function getCarBrandGroup($modelNumber)
{
    if ($modelNumber == 999) {
        return 'Other';
    }

    if (isset(self::$carBrandGroups[$modelNumber[0]])) {
        return self::$carBrandGroups[$modelNumber[0]];
    }

    return 'Unknown';
}

The modelNumber is three digits so everything that starts with 0 is a volvo model, so 001 is Volvo V40, 101 is BMW X6 and so on...

Like I stated above, everything works except for 0, is there a way to make this work and seen as a value?

Thank you in advance.

  • 写回答

2条回答 默认 最新

  • drwu24647 2019-01-25 22:20
    关注

    I'll asume the $modelNumber is a string with 3 characters in it. In your example you're passing $modelNumber[0] and it should result in an error.

    Option 1: split your string into an array

    public static function getCarBrandGroup($modelNumber)
    {
        if ($modelNumber == 999) {
            return 'Other';
        }
        // Split your string into an array
        $modelNumber = str_split($modelNumber);
        if (isset(self::$carBrandGroups[$modelNumber[0]])) {
            return self::$carBrandGroups[$modelNumber[0]];
        }
    
        return 'Unknown';
    }
    

    Option 2: use the first character to get the required model

    public static function getCarBrandGroup($modelNumber)
    {
        if ($modelNumber == 999) {
            return 'Other';
        }
        // Get the first character using substr
        $modelNumber = substr($modelNumber, 0, 1);
        if (isset(self::$carBrandGroups[$modelNumber])) {
            return self::$carBrandGroups[$modelNumber];
        }
    
        return 'Unknown';
    }
    

    Option 3: Or if you like shorthand & fancy PHP7 operators:

    public static function getCarBrandGroup($modelNumber)
    {
        if ($modelNumber == 999) {
            return 'Other';
        }
    
        return self::$carBrandGroups[substr($modelNumber, 0, 1)] ?? 'Unknown';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?