PHP : Array key containing special character not found

前端 未结 2 1946
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-22 11:19

I am trying to convert strings to numbers using an array with keys as a lookup table.

This is the array:

$q2_10_lt = array(\"Full-time worker\" => 1
          


        
相关标签:
2条回答
  • 2021-01-22 11:57

    The string you get from your database layer is not the same string you use as the key. To fix it, use the same string each time.

    Same means here, that the string is the same byte-by-byte. Do a hexdump of the string you get from the database.

    Then enter the binary string as key (or at least for the special letter). This will make your code more robust because it will work regardless in which encoding you're saving the PHP file.

    Edit: As you compare against the database, the key needs to co-related to the binary sequence in the database:

            , "Child attending pre-school/nursery school/cr\xE8che/day-mother" => 10
                                                           ^^^^
    

    Use the hexadecimal notation to express the bytes you are not able to "type" with your UTF-8 encoded PHP file. The database uses some ISO-8859-1 or similar encoding.

    As you can see it is just \x and then the hexcode E8. It works in double-quoted strings in PHP.

    0 讨论(0)
  • 2021-01-22 11:57

    I ended up changing my table column encoding to utf8_general_ci and table collation to utf8_general_ci. I also added the following lines of code to my php file:

    ini_set('default_charset', 'utf-8');
    
    //set encodig to utf-8
    mysql_query("SET NAMES 'utf8'"); 
    mysql_query("SET CHARACTER SET 'utf8'");
    

    It is working now, but I could be doing something not recommended?

    0 讨论(0)
提交回复
热议问题