【问题标题】:How to solve this logic?如何解决这个逻辑?
【发布时间】:2023-03-13 22:40:01
【问题描述】:

我做了一个测试,有这个顺序,如下:

$in = [
[ts->'1', data->'dado 1'];
[ts->'2', data->'dado 2'];
[ts->'3', data->'dado 3'];
]

以下步骤:

  1. 过滤其中 ts > x
  2. 排序 ts
  3. 以 Json 格式输出(这可能使用 echo json_encode($in))

我该如何解决这些步骤?

编辑

也许它会是一个替代解决方案:

//Filter ts
function filtrar($in)
{
    $x = 1;
    return($in['ts'] > $x);
}
//Sort ts
foreach ($in as $key => $row) {
    $ts[$key]  = $row['ts'];
}
array_multisort($ts, SORT_ASC, $in);
//output into Json
echo json_encode(array_filter($in, "filtrar"));

【问题讨论】:

  • 那是什么格式?
  • 第一步,我考虑过使用“filter_var”,但我不确定。就在我认为使用 json_encode 正确的最后一步。
  • 谢谢,fusion3k。根据您的建议,我用另一种可能的解决方案(也许)编辑了我的帖子...

标签: php arrays json sorting


【解决方案1】:

在阅读链接建议后,我得到了一个可能的解决方案:

//Filter ts
function filtrar($in)
{
    $x = 1;
    return($in['ts'] > $x);
}
//Sort ts
foreach ($in as $key => $row) {
    $ts[$key]  = $row['ts'];
}
array_multisort($ts, SORT_ASC, $in);
//output into Json
echo json_encode(array_filter($in, "filtrar"));

在此链接中:array_filter()array_multisort()

【讨论】:

    【解决方案2】:

    玩得开心:)

     $in = [
        ['ts' =>'1', 'data'=>'dado 1'],
        ['ts'=>'2', 'data'=>'dado 2'],
        ['ts'=>'3', 'data'=>'dado 3'],
        ];
    
        $number = 2;
    
        $filtered = array_filter($in , function($to_filter) use ($number) {
            if($to_filter['ts'] >= $number)
                return $to_filter;
        });
    
        print_r($filtered);
    

    【讨论】:

      【解决方案3】:

      你有没有尝试过?这是一个想法:

      $buffer = array();
      $in = json_decode($in);
      foreach ($in as $row)
      {
         if ($row['ts'] > 1)
         {
            $buffer[$row['ts']] = $row;
         }
      }
      
      ksort($buffer);
      var_dump($buffer);
      

      【讨论】:

      • 这行$in = json_decode($in); 会导致错误。对于测试,我认为排除它并包含在最终的echo json_encode($in); 中是有意义的。你怎么看?
      猜你喜欢
      • 1970-01-01
      • 2013-09-29
      • 2021-06-12
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多