将array_count _values与JSON数组一起使用

时间:2017-08-19 15:11:29

标签: php

我有一个脚本,我正在使用XML更新为JSON。使用XML时,此脚本运行正常。我在使用JSON时遇到了一些问题。我可以回显循环中的变量,它返回值,所以我知道它正确解析它。不幸的是,它无法计算所有值并将单个数字返回给总值。使用JSON而不是XML时,我需要做些什么。

以下是两个片段,一个是使用XML作为数据源的工作解决方案。另一个是我无法使用JSON的解决方案,这是我需要工作的。我必须在JSON解决方案中提到我在循环之前过滤值,在XML解决方案中它是在循环后过滤的。所以在JSON解决方案中应该非常简单。只计算返回值的数量。我只是无法让它发挥作用。我尝试了count(),只返回值1。所以我决定将它插入array_count_values并让它计算那些整数并且不起作用。

XML解决方案 - WORKS

    // Lets parse the feed
$dom = new DOMDocument();
$dom->load($data3);

$events = [];
foreach ($dom->getElementsByTagNameNS("urn:oasis:names:tc:emergency:cap:1.1", "event") as $event) {
    $events[] = $event->nodeValue;
}

    $counts = array_count_values($events);//lets count the results
    $value = @$counts["Tornado Warning"] + @$counts["Severe Thunderstorm Warning"] + @$counts["Flash Flood Warning"] + @$counts["Flood Warning"] + @$counts["Tropical Storm Warning"] + @$counts["Hurricane Warning"];


$showCounts = '<i class="fa fa-exclamation-triangle severe-icon__tornado"></i> NATIONAL WARNINGS <span class="badge" style="margin-bottom:2px;">' . $value. '</span>';

$showTitle = '<i class="fa fa-exclamation-triangle severe-icon__tornado"></i> NATIONAL WARNINGS';


if($value == "0") {
    echo $showTitle;
} else {
    echo $showCounts;
}

JSON解决方案 - 无法正常工作

$str = file_get_contents($url); // put the contents of the file into a variable
$o=json_decode($str,true);
$features=$o['features'];

//Lets filter the response to get only the values we want
$filtered= array_filter($features,function($el){
    $alerts = array('Tornado Warning', 'Severe Thunderstorm Warning', 'Hurricane Warning', 'Tropical Storm Warning', 'Flash Flood Warning', 'Flood Warning');
    return in_array($el['properties']['event'],$alerts);});

$events = [];

//Lets loop through the array
foreach($filtered as $currFeature)
{

    $events[] = $currFeature['properties']['event'];

}

    $counts = array_count_values($events);//lets count the results

$showCounts = '<i class="fa fa-exclamation-triangle severe-icon__tornado"></i> NATIONAL WARNINGS <span class="badge" style="margin-bottom:2px;">' . $value. '</span>';

$showTitle = '<i class="fa fa-exclamation-triangle severe-icon__tornado"></i> NATIONAL WARNINGS';

if($counts == "0") {
    echo $showTitle;
} else {
    echo $showCounts;
}

1 个答案:

答案 0 :(得分:0)

我通过在XML解决方案中添加以下行来解决这个问题,但是在JSON解决方案之外。我添加了这个,现在又恢复了。

$value = @$counts["Tornado Warning"] + @$counts["Severe Thunderstorm Warning"] + @$counts["Flash Flood Warning"] + @$counts["Flood Warning"] + @$counts["Tropical Storm Warning"] + @$counts["Hurricane Warning"];