将 JSON 结果分组到类别中
Posted
技术标签:
【中文标题】将 JSON 结果分组到类别中【英文标题】:Grouping JSON results into categories 【发布时间】:2022-01-18 23:06:51 【问题描述】:我正在尝试从 JSON 结果集中对一些类似的数字进行分组。我需要将所有 [1, X] 分组到小型/大型组中,将 [0, X] 分组到小型/中型/大型组中。
我认为我需要对数据进行一些预处理并找到数据的平均值或钟形曲线?
$results = json_decode("data": [[0, 2960], [1, 768], [0, 592], [1, 384], [0, 592], [1, 400], [0, 208], [1, 384], [0, 208], [1, 384], [0, 320], [1, 1056], [0, 576], [1, 400], [0, 208], [1, 384], [0, 592], [1, 768], [0, 208], [1, 400], [0, 592], [1, 768], [0, 208], [1, 768], [0, 208], [1, 400], [0, 1360], [1, 384], [0, 208], [1, 400], [0, 192], [1, 784], [0, 208], [1, 384], [0, 592], [1, 768], [0, 224], [1, 768], [0, 208], [1, 768], [0, 592], [1, 384], [0, 208], [1, 768], [0, 224], [1, 368], [0, 1376], [1, 784], [0, 208], [1, 384], [0, 224], [1, 768], [0, 208], [1, 768], [0, 592], [1, 768], [0, 224], [1, 768], [0, 208], [1, 768], [0, 592], [1, 400], [0, 96], [1, 16], [0, 16], [1, 464], [0, 32], [1, 944], [0, 1968], [1, 0]]);
foreach($flashes as $values)
$flash_status = $values[0];
$length = $values[1];
// flashing
if($flash_status == 1)
if($length is short)
// do something
elseif($length is long)
// do something
else
// pausing
if($length is short)
// do something
elseif($length is medium)
// do something
elseif($length is long)
// do something
【问题讨论】:
你如何定义什么是短/中/长? 【参考方案1】:这就是最终为我工作的原因。对于 180 跳跃仍有硬编码检查,但它现在可以满足我的需要。
array_multisort($ordering, array_column($ordering, 0));
$flash_categories = array(
1 => array (
'short' => array('min'=> 0,'max'=> 0,),
'long' => array('min'=> 0,'max'=> 0,),
),
0 => array (
'short' => array('min'=> 0,'max'=> 0,),
'medium' => array('min'=> 0,'max'=> 0,),
'long' => array('min'=> 0,'max'=> 0,),
),
);
$previous_value = 0;
$previous_flash = 0;
$flash_heading_index = 0;
$flash_headings = array(
1 => array ('short','long'),
0 => array ('short','medium','long'),
);
foreach($ordering as $values)
$flash_status = $values[0];
$length = $values[1];
// skip errors
if($length < 100 || $length > 2000)
continue;
if($previous_flash != $flash_status)
$previous_flash = $flash_status;
$flash_heading_index = 0;
$previous_value = 0;
// check to see how much difference there is in time
if($length - $previous_value > 180 && $previous_value != 0)
$flash_heading_index++;
// cap off the heading index
if(!isset($flash_headings[$flash_status][$flash_heading_index]))
$flash_heading_index = sizeof($flash_headings[$flash_status])-1;
// set min and max threshold to values
if($flash_categories[$flash_status][$flash_headings[$flash_status][$flash_heading_index]]['min'] == 0)
$flash_categories[$flash_status][$flash_headings[$flash_status][$flash_heading_index]]['min'] = $length;
$flash_categories[$flash_status][$flash_headings[$flash_status][$flash_heading_index]]['max'] = $length;
else
$flash_categories[$flash_status][$flash_headings[$flash_status][$flash_heading_index]]['max'] = $length;
$previous_value = $length;
【讨论】:
以上是关于将 JSON 结果分组到类别中的主要内容,如果未能解决你的问题,请参考以下文章