2014-05-13 3 views
1

두 변수 $ state 및 $ sectors를 사용하여 스크립트를 만들었습니다. 상태가 해당 섹터에 있으면 해당 섹터를 표시하려고합니다. 아래의 예는 상태로 '애리조나'를 사용하며 출력 '남서'등의 분야를해야하지만 난 제대로 배열하고 있어요 생각하지 않는다 :하위 배열의 값이있는 경우 상위 키 표시

<?php 

    $state = 'Arizona'; 

    $sectors = array(
       "Southeast" => array(
         'name' => 'Southeast', 
         'states' => array('Alabama', 'Georgia', 'Florida', 'South Carolina', 'North Carolina', 'Louisiana', 'Tennessee', 'Kentucky', 'West Virginia', 'Mississippi') 
       ), 
        "Southwest" => array(
          'name' => 'Southwest', 
          'states' => array('California', 'Arizona', 'New Mexico', 'Utah') 
        ) 
    ); 

     function has_recursive($sectors, $state) 
     { 
      foreach ($state as $key => $value) { 
       if (!isset($sectors[$key])) { 
        return false; 
      } 
      if (is_array($sectors[$key]) && false === has_recursive($sectors[$key], $value)) { 
       return false; 
      } 
     } 
     return true; 
    } 

    if (has_recursive($sectors, $state) == true){ 
    // false or true 
     echo $sector['name']; // Displays Southwest 
    } 

이 도와주세요.

+0

당신은 확실히 ''국가 '=> 배열 ('캘리포니아 ','애리조나 ','뉴 멕시코 ','유타 ')'을 의미 ? ("array (...)"를 참고하십시오) – bwoebi

+0

"Southeast"=> array ('Alabama', 'Georgia', 'Florida', 'South Carolina', 'North Carolina', 'Louisiana' ','Tennessee ','Kentucky ','West Virginia ','Mississippi ')'$ 섹터를 검색하는 방법 – Rizzo

+0

@Rizzo 예 – bwoebi

답변

0

이 시도 :

귀하의 질문에 정의 된 $state$sectors을 감안할 때
function get_sector($sector_array, $state_name) { 

    foreach ($sector_array as $sec) 
     if (in_array($state_name, $sec)) 
      return $sec['name']; 

    return false; 
} 

... 코멘트에 대한

echo get_sector($sectors, $state); // prints "Southwest" 

업데이트 : 몇 가지 다른 방법이 있습니다

"찾을 수 없음"반환 값. 어떤 응용 프로그램에 가장 적합한 것은 당신에게 달려 있지만, 여기에 몇 가지 예입니다 :

return false; 

//This would be used like this: 
if (!$sect = get_sector($sectors, $state)) 
    echo "A custom error message" 
else 
    echo "Sector = " . $sect; 

또는 특정 문자열을 반환 할 수 있습니다 :

return "Sector not found."; 
// Return a standard error message 

또는 사용자 정의 문자열 :

return "No sector match for the state of " . $state_name; 
// Return a specific error message 
+0

허위 인 경우 비워 둡니까? – Rizzo

+0

@Rizzo 발견되지 않으면 False가 원래 생각이었습니다. 일치하지 않는 경우 대신 "Sector not found"를 반환하는 함수를 업데이트했습니다. –

+0

@Rizzo 반환 값에 대한 자세한 정보로 다시 업데이트되었습니다. –

0

이 함수는 작동해야합니다. 코드에서 사용

function getSector($stateName, $sectorList) { 
    foreach($sectorList as $sector) { 
     if(in_array($stateName, $sector['states']) { 
     return $sector['name']; 
     } 
    } 
// If state is not found 
return 'NOT FOUND'; 
} 

예는 다음과 같습니다

echo getSector($state, $sectors); 
+0

앞서 언급 한 [다른 답변] (http://stackoverflow.com/a/23639882/)과의 차이점은 거의 없습니다. 반환 값이 약간 다를 경우 기능이 100 % 동일합니다. –

관련 문제