php
  • arrays
  • 2013-07-07 118 views 0 likes 
    0

    我試圖通過搜索它的值從數組中獲得密鑰。在下面的代碼中,我不明白爲什麼array_search()$url文件擴展名是"xls"時找不到密鑰,但是當它是"php"時它可以。我注意到類似的問題,無法使用in_array()array_keys()「找到」"xls"php array_search關聯數組

    $url='http://mysite.com/hello.xls'; 
    $url='http://mysite.com/hello.php'; 
    
    $extension_arr=pathinfo($url); 
    $extension=strtolower($extension_arr['extension']); 
    
    $arr=array(
        'excel_file'=>'xls', 
        'excel_file'=>'xlsx', 
        'php_file' =>'php' 
    ); 
    
    $array_search_key=array_search($extension, $arr); 
    if($array_search_key !== false){ 
        echo $array_search_key; 
    } 
    else echo 'crap'; 
    
    +1

    你需要翻轉數組的鍵和值,這是不可能的一個以上的值與關聯一個給定的鍵。您可以使用['isset()'](http://php.net/isset)在交換鍵和值時執行所需的功能。 – DaveRandom

    +0

    @DaveRandom謝謝。看起來這也可以通過給每個鍵設置自己的唯一值來解決,比如「excel_file xls''和」excel_file xlsx''。你介意做出一個回答翻轉鍵和值的答案嗎? –

    回答

    3

    您的搜索有效,但您搜索的數組有缺陷。元素1(xlsx)覆蓋元素0,因爲鍵是相同的。

    $arr=array(
        'excel_file'=>'xls', 
        'excel_file'=>'xlsx', // This overwrites the line above. 
        'php_file' =>'php' 
    ); 
    

    翻轉的元素周圍,那麼你可以檢查項是否存在:

    $arr=array(
        'xls'=>'excel_file', 
        'xlsx'=>'excel_file', 
        'php'=>'php_file' 
    ); 
    
    if (isset($arr[$extension])) { 
        // do stuff 
        echo $arr[$extension]; 
    } 
    
    +0

    你也可以去找一個'excel_files'數組,這可能會更有效。 –

    0

    首先嚐試調試$擴展如果顯示想要的值(XLS),嘗試交換鍵和纈氨酸,並嘗試通過新的關鍵發現:

    $aux = array(); 
    
    foreach($arr as $key => $val) 
    { 
        $aux[ $val ] = $key; 
    } 
    

    所以你試圖找到當前值:

    if (isset(@$aux[ $extension ])) echo "I found the current extension"; 
    else "extension not found!"; 
    
    +0

    Isset不是必需的,你可以只要(@ $ aux [$ extension]) –

    +4

    你應該使用isset並移除閉合運算符@。好習慣。 – apartridge

    相關問題