2012-07-27 3 views
2

URL을 기반으로 간단한 배열을 만들었습니다. 즉 www.example.com/apple/입니다. 필자가 필요로하는 곳에 사과 텍스트를 넣습니다.하지만 필자는 브랜드를 기반으로 고정 된 텍스트 고정 분리.PHP 배열 - 대체 출력

IE 그래서 $ brand_to_use를 사용하여 "apple"에 배치하고 $ brandurl_to_use를 사용하여 "apple.co.uk"에 그릴 수 있습니다.하지만이 위치를 필요한 곳에 "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://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]; 

, 그것을 얻기 위해 시작 :

$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

+0

다음과 같이 진행합니다 :'reset'과'key'를 사용하면 가장 빠르고 메모리 효율적인 솔루션을 제공합니다 :) –

0

나는 무엇을 당신이하고자하는 것은이 같은 것입니다 생각 아주 지저분 해. 하지만 다음과 같이 할 수 있습니다 :

+0

'in_array()는 일치하는 값이 아닌 일치하는 값을 찾습니다 –

+0

@WouterH Darnit 'isset()'그리고 잊어 버렸습니다. 감사. – DaveRandom

+0

@WouterH Fixed ;-) – DaveRandom