2017-08-13 79 views
-1

我正在嘗試使用array_filter來過濾某些值並禁止其餘的值。我從來沒有使用過array_filter,所以我一直在試圖將我的標題包裹在這裏。PHP:如何使用array_filter()過濾JSON響應值?

我需要首先篩選值之前循環通過它,如果是這樣我會過濾數組只查找這些值。

這是目前我正在使用的代碼片段,它正在反彈錯誤。 $ alerts是我只需從數組中返回的值,同時禁止其他值。然後我循環過濾結果。在我的腦海中,這似乎是合乎邏輯的,但我相信我錯過了某些東西,因爲它不起作用。

$data = file_get_contents($url); // put the contents of the file into a variable 
$results = json_decode($data, true); // decode the JSON feed 

$alerts = array(Tornado Warning, Severe Thunderstorm Warning, Flash Flood Warning, Flood Warning); 

$selected_events = array_filter($results['features'], function($data) { 
     return $data === $alerts; 
    }); 

//Lets loop through the array 
foreach($selected_events as $currFeature) 
{ 
    $event = $currFeature['properties']['event']; 
    $wfo = $currFeature['properties']['sender']; 
    $area = $currFeature['properties']['areaDesc']; 
    $expires = $currFeature['properties']['expires']; 

這是我正在使用的JSON的一個示例。

{ 
"@context": [ 
    "https://raw.githubusercontent.com/geojson/geojson-ld/master/contexts/geojson-base.jsonld", 
    { 
     "wx": "https://api.weather.gov/ontology#", 
     "@vocab": "https://api.weather.gov/ontology#" 
    } 
], 
"type": "FeatureCollection", 
"features": [ 
    { 
     "id": "https://api.weather.gov/alerts/NWS-IDP-PROD-2485744-2320592", 
     "type": "Feature", 
     "geometry": { 
      "type": "Polygon", 
      "coordinates": [ 
       [ 
        [ 
         -96.77, 
         33.84 
        ], 
        [ 
         -96.76, 
         33.82 
        ], 
        [ 
         -96.71, 
         33.83 
        ], 
        [ 
         -96.52, 
         33.82 
        ], 
        [ 
         -96.5, 
         33.77 
        ], 
        [ 
         -96.43, 
         33.78 
        ], 
        [ 
         -96.38, 
         33.73 
        ], 
        [ 
         -96.39, 
         33.45 
        ], 
        [ 
         -96.42, 
         33.46 
        ], 
        [ 
         -96.94, 
         33.54 
        ], 
        [ 
         -96.94, 
         33.85 
        ], 
        [ 
         -96.77, 
         33.84 
        ] 
       ] 
      ] 
     }, 
     "properties": { 
      "@id": "https://api.weather.gov/alerts/NWS-IDP-PROD-2485744-2320592", 
      "@type": "wx:Alert", 
      "id": "NWS-IDP-PROD-2485744-2320592", 
      "areaDesc": "Grayson", 
      "geocode": { 
       "UGC": [ 
        "TXC181" 
       ], 
       "SAME": [ 
        "048181" 
       ] 
      }, 
      "references": [], 
      "sent": "2017-08-13T13:18:17+00:00", 
      "effective": "2017-08-13T13:18:17+00:00", 
      "onset": "2017-08-13T13:18:00+00:00", 
      "expires": "2017-08-13T16:15:00+00:00", 
      "ends": "2017-08-13T16:15:00+00:00", 
      "status": "Actual", 
      "messageType": "Alert", 
      "category": "Met", 
      "severity": "Severe", 
      "certainty": "Likely", 
      "urgency": "Expected", 
      "event": "Flood Warning", 
      "sender": "NWS Fort Worth TX", 
      "headline": "Flood Warning issued August 13 at 8:18AM CDT expiring August 13 at 11:15AM CDT by NWS Fort Worth TX", 
      "description": "The National Weather Service in Fort Worth has issued a\n\n* Flood Warning for...\nGrayson County in north central Texas...\n\n* Until 1115 AM CDT\n\n* At 816 AM CDT, Emergency management reported flooding of several\nroadways across Grayson County. While the heaviest rainfall has\nended...excessive runoff will continue to result in\nstreams...creeks and some rivers exceeding their banks across the\narea.\n\n* Some locations that will experience flooding include...\nSherman, Denison, Whitesboro, Howe, Pottsboro, Collinsville,\nWhitewright, Bells, Tom Bean, Knollwood, Dorchester, Eisenhower\nState Park, southeastern Lake Texoma, Southmayd, Sadler and Luella.", 
      "instruction": "A Flood Warning means that flooding is imminent or occurring. Water\nrises will generally be gradual, but flooding of some low water\ncrossings and other low-lying areas near rivers, creeks, and streams\nis expected.", 
      "response": "Avoid", 
      "parameters": { 
       "VTEC": [ 
        "/O.NEW.KFWD.FA.W.0008.170813T1318Z-170813T1615Z/" 
       ], 
       "EAS-ORG": [ 
        "WXR" 
       ], 
       "PIL": [ 
        "FWDFLWFWD" 
       ], 
       "BLOCKCHANNEL": [ 
        "CMAS", 
        "EAS", 
        "NWEM" 
       ], 
       "eventEndingTime": [ 
        "2017-08-13T16:15:00Z" 
       ] 
      } 
     } 
    }, 

回答

-1

您的$alerts陣列的定義在其目前的格式中是不正確的。您應該將可能的值附於"',請參閱下面的解決方案。

你可以做到以下幾點:

$o=json_decode($str,true); // $str is the JSON string 
$features=$o['features']; 
$filtered= array_filter($features,function($el){ 
    $alerts = array('Tornado Warning', 'Severe Thunderstorm Warning', 'Flash Flood Warning', 'Flood Warning'); 
    return in_array($el['properties']['event'],$alerts);}); 

json_encode(...,true)會產生一個關聯數組(而不是對象)。過濾器函數然後檢查數組$features中的元素的可能['properties']['event']屬性。只有那些在$alerts陣列中找到的值(我爲此使用in_array())將通過篩選過程。

如果你喜歡,你還可以定義$alerts陣列實際過濾功能外,只引用它有這樣的:

.. 
... 
$alerts = array('Tornado Warning', 'Severe Thunderstorm Warning', 
       'Flash Flood Warning', 'Flood Warning'); 
$filtered= array_filter($features,function($el) use ($alerts) { 
    return in_array($el['properties']['event'],$alerts);}); 

你可以找到一個演示在這裏工作:http://rextester.com/EELE62798

+0

能否downvoter請解釋,爲什麼? – cars10m

+0

我沒有投票。我很欣賞這種迴應。最有可能的是收回2票的其他人收回了2票。關於它給我以下錯誤的代碼。 str是未定義的,array_filter()期望參數1是數組,null指的是你的最後一行代碼,以return in_array開頭。 – Texan78

+0

我的'$ str'應該等於你的'$ data'。我在rextester.com演示的基礎上開發了我的解決方案。所以,只要你在'$ str'中有一個有效的JSON字符串,我的代碼就可以工作。您指定的JSON字符串實際上缺少關閉']}' - 請參閱我的演示。 – cars10m