dongyou8368 2019-04-04 18:55
浏览 52
已采纳

我需要实现接受颜色作为字符串参数的函数,并将其作为json_encode返回

I want to get the function that can accept a string parameter and return it to json format. for example if i call $ballcolor->getBall("orange"); then the output// should be: { "color":"orange", "ball": ["basketball"]}

and if a call does not have any color for that ball: { "color":"black", "ball": []}

class BallColor
    {
      private $ballcolor;

      function BallColor($ballcolor)
      {
        $this->ballcolor = $ballcolor;
      }

      public function getBall($color)
      {

        return NULL;

      }
    }

    $ballcolor = new BallColor(array(
        "orange" => array("basketball"),
        "white" => array("football")
    ));

    echo $ballcolor->getBall("orange");
    echo "
";
    echo $ballcolor->getBall("black");
  • 写回答

2条回答 默认 最新

  • duanjiati1755 2019-04-04 19:13
    关注

    Get the desired value out of $this->ballcolor after checking it's there, then build the array you need to return, then json_encode that:

    class BallColor
    {
          private $ballcolor;
    
          function __construct($ballcolor)
          {
            $this->ballcolor = $ballcolor;
          }
    
          public function getBall($color)
          {
              // condensed into oneliners:
              if(isset($this->ballcolor[$color])) {
                  return json_encode(Array("color" => $color, "ball" => $this->ballcolor[$color]));
              } else {
                  return json_encode(Array("color" => "black", "ball" => []));
              }
          }
    }
    
    $ballcolor = new BallColor(array(
        "orange" => array("basketball"),
        "white" => array("football")
    ));
    
    echo $ballcolor->getBall("orange");
    echo "
    ";
    echo $ballcolor->getBall("black");
    

    Output:

    {"color":"orange","ball":["basketball"]} 
    {"color":"black","ball":[]}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 深度学习运行代码直接中断
  • ¥15 关于#单片机#的问题,请各位专家解答!
  • ¥15 关于#单片机#的问题,请各位专家解答!
  • ¥20 需要完整的共散射点成像代码
  • ¥15 编写vba代码实现数据录入工作
  • ¥15 做过TCL海信电视小米电视相关影视会员软件私我
  • ¥15 Mapreduce是正常的,在运行其他jar包时并没有任何问题,只是在做LogCount.jar 时出的问题。如图所示
  • ¥15 ImportError: DLL load failed while importing _iterative: 找不到指定的模块。
  • ¥15 如何通过交互分析得出某高危患者对放疗获益更多
  • ¥15 相关性分析中,p<0.05, r=0.29,怎么评价相关性呢