2016-11-15 88 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