【问题标题】:foreach key -> value outside foreachforeach 键-> foreach 之外的值
【发布时间】:2016-11-15 10:28:23
【问题描述】:

如何访问特定的“键”及其关联的“值”,以便稍后在 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 循环内工作并正确打印了电话和城市值 - 但我希望能够在此循环之外打印这些值。

【问题讨论】:

    标签: php arrays foreach custom-fields


    【解决方案1】:
    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> ';
    

    【讨论】:

    • 哇 - 谢谢 - 效果很好 - 你让它看起来如此简单!非常感谢;-)
    猜你喜欢
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多