2012-08-14 21 views
0

我試圖建立一個飼料發電機掛鉤到api。我試圖掛接到API建立在以下網址格式:如何構建一個複雜的URL/feed,將內部選項包含在圓括號中?

http://the.apiurl.com/f/query/?q=((((((rating%3A%3E%3D3)%20and%20rev_enabled)%20and%20not%20tags%3Arandomtag)%20and%20languages%3Aen)%20and%20this_enabled)%20and%20that_enabled)%20and%20this_also_enabled&_id=xxxx&limit=100 

正如你可以看到,該內部供選項被包裹在括號中。如果你要提出一個內部選項,你仍然會留下其他必須包裹在括號中的選項嗎?

有沒有一些PHP絕地心靈詭計的方式實現這個最終結果與優雅?或者我是否必須簡單地構建一個可笑的if/else/ifelse循環?

謝謝!

回答

0

嗯,我花了一些時間來處理這個問題。下面是我能想到的最好的。基本上,該函數接受一個填充了鍵/值對的必要參數的數組。它首先遍歷參數/ s來查找總數,然後在前端應用必要的括號。然後它通過一系列循環解析參數並在必要時附加它們。

該解決方案特定於Mochi Feed API,但如果您稍微調整它,則可以以其他方式使用該解決方案。

// Accepts: $params (array) - An array which contains all of the filter options we are trying to account for. 
function process_feed($params=null) { 

    // Grab our feed's base URL 
    $url = 'http://the.apiurl.com/f/query/?q='; 

    // The items stored in this array can be set to a boolean value (true or false) 
    $bool_queries = array('rev_enabled', 'this_enabled', 'this_also_enabled'); 

    // The items stored in this array can be set to an integer, string, etc... 
    $return_queries = array('languages', 'omit_tags', 'tags', 'category', 'limit'); 

    // Grab the parameter/filter count 
    $size = count($params); 

    // We have enough filters to go custom 
    if ($size > 1) { 

     // Loop through and place the appropriate amount of opening parens 
     for ($x = 0; $x < ($size-1); $x++) { $url .= '('; } 

     $i = 0; 

     foreach ($params as $key=>$value) { 

      if ($i < ($size-1)) { 

       if (in_array($key, $bool_queries)) { 
        $url .= $key.')%20and%20'; 
       } else { 

        // special NOT case 
        if ($key == 'omit_tags') { 
         $url .= 'not%20tags%3A'.$value.')%20and%20'; 
        } else { 
         $url .= $key.'%3A'.$value.')%20and%20'; 
        } 
       } 

      } else { 
       if (in_array($key, $bool_queries)) { 
        $url .= $key; 
       } else { 
        // special NOT case 
        if ($key == 'omit_tags') { 
         $url .= 'not%20tags%3A'.$value; 
        } else { 
         $url .= $key.'%3A'.$value; 
        } 
       } 
      } 

      $i++; 
     } 

    } else if ($size == 1) { 

     foreach ($params as $key=>$value) { 
      if (in_array($key, $bool_queries)) { 
       $url .= $key; 
      } else { 
       // special NOT case 
       if ($key == 'omit_tags') { 
        $url .= 'not%20tags%3A'.$value; 
       } else { 
        $url .= $key.'%3A'.$value; 
       } 
      } 
     } 
    } 

    if (isset($params['limit'])) { 
     $url .= '&partner_id=' . $our_partner_key . '&limit=' . $limit; 
    } else { 
     $url .= '&partner_id=' . $our_partner_key; 
    } 

    if(isset($url)) { 
     return $url; 
    } 

    return false; 
} 
相關問題