【问题标题】:Understanding coderbyte back-end challenge了解 coderbyte 后端挑战
【发布时间】:2023-01-24 18:09:38
【问题描述】:

这就是挑战:在 PHP 文件中,编写一个程序在路由 https://coderbyte.com/api/challenges/json/age-counting 上执行 GET 请求,其中包含一个数据键,值是一个字符串,其中包含以下格式的项目:key=STRING, age=INTEGER。您的目标是计算存在的年龄等于或大于 50 的项目的数量,并打印此最终值。

示例输入 {"data":"key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47"}

函数运行后,获取最终输出字符串并将 ChallengeToken 中出现的所有字符替换为 --[CHAR]--。

您的挑战代币:ndv946kie1

这是我的代码:

<?PHP 

$ch = curl_init('https://coderbyte.com/api/challenges/json/age-counting');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);

//print_r(json_decode($data, true));
$arr = json_decode($data, true);
$items = explode(', ', $arr['data']);
$count = 0;

foreach ($items as $item){
 //print_r($item . PHP_EOL);
 if(str_starts_with($item,'age=')===true){
   $age = explode('=',$item)[1];
   if($age >= 50)
     $count++;
   }
}

$str = 'ndv946kie1';
$chars = str_split($str);
$final = '';
foreach ($chars as $char){
   $final = $final . $count;
}
print_r($final);
?>

coderbyte 说输出不正确,也许我误解了最后一条指令?

【问题讨论】:

    标签: php


    【解决方案1】:

    请试试这个

    
      $ch = curl_init('https://coderbyte.com/api/challenges/json/age-counting');
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_HEADER, 0);
      $data = curl_exec($ch);
      curl_close($ch);
    
      $json_data = json_decode($data, true);
      $items = explode(', ', $json_data['data']);
      $count = array_reduce($items, function ($count, $item) {
        if (strpos($item, 'age=') !== false) {
          $age = explode('=', $item)[1];
          if ($age >= 50) return $count + 1;
        }
        return $count;
      }, 0);
    
      print_r($count);
    

    【讨论】:

      【解决方案2】:

      我有同样的问题... 在下面给出对我有用的代码:

          <?php 
      $ch = curl_init('https://coderbyte.com/api/challenges/json/age-counting');
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_HEADER, 0);
      $data = curl_exec($ch);
      curl_close($ch);
      
      //print_r(json_decode($data, true));
      $arr = json_decode($data, true);
      $items = explode(', ', $arr['data']);
      $count = 0;
      
      foreach ($items as $item){
       //print_r($item . PHP_EOL);
       if(str_starts_with($item,'age=')===true){
         $age = explode('=',$item)[1];
         if($age >= 50)
           $count++;
         }
      }
      
      print_r($count);
      ?>
      

      【讨论】:

      • 如果您能提供一些细节或解释您的代码为何正确,那就太好了。此外,不确定是否相关,但您的代码不满足提示的最后要求:“一旦您的函数正常工作,获取最终输出字符串并将出现在您的 ChallengeToken 中的所有字符替换为 --[CHAR]--。”
      猜你喜欢
      • 1970-01-01
      • 2016-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-20
      • 1970-01-01
      • 2019-12-28
      • 2019-01-28
      相关资源
      最近更新 更多