2012-07-27 66 views
2

我有一個簡單的數組工作的基礎上的網址,即www.example.com/apple/它放置在我需要它的蘋果文本 - 但我也需要粘貼在一個選項根據品牌分開固定的一段文字。PHP陣列 - 替代輸出

IE所以我可以用$ brand_to_use來繪製它,例如放在「apple」中,$ brandurl_to_use在我需要的地方繪製「apple.co.uk」,但我不知道如何將它添加到基於原始品牌的陣列。

由於

$recognised_brands = array( 
    "apple", 
    "orange", 
    "pear", 
    // etc 
); 

$default_brand = $recognised_brands[0]; // defaults brand to apple 

$brand_to_use = isset($_GET['brand']) && in_array($_GET['brand'], $recognised_brands) 
    ? $_GET['brand'] 
    : $default_brand; 

僞代碼更新例如:

recognised brands = 
apple 
orange 
pear 

default brand = recognised brand 0 


recognised brandurl = 
apple = apple.co.uk 
orange = orange.net 
pear = pear.com 



the brandurl is found from the recognised brands so that in the page content I can reference 

brand which will show the text apple at certain places + 
brandurl will show the correct brand url related to the brand ie apple.co.uk 

回答

1

創建陣列作爲鍵/值對和搜索的陣列中的密鑰。如果你喜歡,每一對的價值部分可以是一個對象。

$recognised_brands = array( 
    "apple" => "http://apple.co.uk/", 
    "orange" => "http://orange.co.uk/", 
    "pear" => "http://pear.co.uk/", 
    // etc 
); 

reset($recognised_brands); // reset the internal pointer of the array 
$brand = key($recognised_brands); // fetch the first key from the array 

if (isset($_GET['brand'] && array_key_exists(strtolower($_GET['brand']), $recognised_brands)) 
    $brand = strtolower($_GET['brand']); 

$brand_url = $recognised_brands[$brand]; 
+0

在這裏值得注意的是,數組解引用(即'array_keys($ default_brand)[0]')只能在5.4中工作 - 這正是我將該操作分成兩行的原因。 'array_keys()'方法雖然不會影響數組指針,但可能會更好,但如果'$ recognised_brands'非常大,則可能會降低內存的效率。儘管如此,我想我會給予你+1的回答。 – DaveRandom 2012-07-27 09:02:50

+0

在這裏你可以:使用'reset'和'key'爲你提供最快,效率最高的解決方案:) – 2012-07-27 09:07:09

0

認爲什麼你想要做的是這樣的:

$recognised_brands = array( 
    "apple" => 'http://www.apple.co.uk/', 
    "orange" => 'http://www.orange.com/', 
    "pear" => 'http://pear.php.net/', 
    // etc 
); 

$default_brand = each($recognised_brands); 
$default_brand = $default_brand['key']; 

$brand = isset($_GET['brand'], $recognised_brands[$_GET['brand']]) 
    ? $_GET['brand'] 
    : $default_brand; 
$brand_url = $recognised_brands[$brand]; 

如果要動態地設置默認品牌數組的第一個元素,它開始變得凌亂得很快。但你可以這樣做:

+0

'in_array()'尋找匹配值,而不是匹配鍵 – 2012-07-27 08:57:58

+0

@WouterH Darnit,意在改變它'isset()'忘了。謝謝。 – DaveRandom 2012-07-27 08:58:33

+0

@WouterH固定;-) – DaveRandom 2012-07-27 08:59:41