2012-07-27 68 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