2016-11-15 89 views
1

如何訪問特定「鍵」及其關聯的「值」,以便在以後的foreach循環之外使用?foreach鍵 - > foreach外的值

這是數組;

Array ([0] => 
CustomFields 
[1] => stdClass Object 
    ([Key] => Phone [Value] => 5555555) 
[2] => stdClass Object 
    ([Key] => City [Value] => New York) 
[3] => stdClass Object 
    ([Key] => State [Value] => NY) 
[4] => stdClass Object 
    ([Key] => Cellphone [Value] => 222444555) 

而這裏是我正在使用的查詢;

$cf = array(); 
foreach($result->response->CustomFields as $data) { 

    $cf [] = $data; 

     if ($cf [] = ($data->Key == 'Phone')) { 
      echo 'Your Phone number is:'.$data->Value.'<br> '; 
     } 

      if ($cf [] = ($data->Key == 'City')) { 
      echo 'Your City is: '.$data->Value.'<br> '; 
     } 
} 

我的查詢工作foreach循環內,正確地打印手機和城市價值 - 但我想能夠打印這個循環之外這些值。

回答

2
function findByKeyInCollection($key, $collection){ 
    foreach($collection as $data) { 
     if ($data->Key == $key) { 
      return $data; 
     } 
    } 
} 
$phone = findByKeyInCollection("Phone", $result->response->CustomFields); 
echo 'Your Phone number is:'.$phone->Value.'<br> '; 
+0

哇 - 謝謝 - 完美的作品 - 讓你看起來很簡單!非常感激 ;-) – Sol