2016-11-16 72 views
2

我有存儲在數據庫中的以下格式的URL提取特定的數據

index.php?main_page=product_info&cPath=1_11&products_id=568

我希望能夠提取CPATH數據,1_11在這種情況下,產品ID「 568'分爲兩個單獨的變量。請注意,cPath值可以從單個數字(如23)變爲一系列數字和下劃線(如17_25_31)。如果提取cPath太困難,我可以在提取後再使用products_id並再次查詢數據庫,但這並不理想,因爲我想盡可能避免附加請求。

我真的不知道最好(正確)的方式去做這件事。

回答

4

由羅比Averill的建議更精確的方法

//first lets the the query string alone 
$string=parse_url('index.php?main_page=product_info&cPath=1_11&products_id=568', PHP_URL_QUERY); 

parse_str($string,$moo); 

print_r($moo); 

輸出:

Array 
(
    [main_page] => product_info 
    [cPath] => 1_11 
    [products_id] => 568 
) 

我原來的建議。

parse_str('index.php?main_page=product_info&cPath=1_11&products_id=568',$moo); 

print_r($moo); 

輸出:

Array 
(
    [index_php?main_page] => product_info 
    [cPath] => 1_11 
    [products_id] => 568 
) 
+1

更好的將可能是'parse_url'第一然後就'查詢字符串 –

+1

我想過parse_str',但他只想'cPath'和'products_id'所以我認爲讓它變得很簡單。但我會補充說,答案;-) – 2016-11-16 02:59:35

+0

工程很漂亮,謝謝。很容易將值賦給變量$ cPath =($ moo ['cPath']); $ products_id =($ moo ['products_id']); –