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

时间:2019-04-04 18:55:10

标签: php json

我想获得可以接受字符串参数并将其返回为json格式的函数。 例如,如果我调用$ ballcolor-> getBall(“ orange”); 那么输出//应该是: {“ color”:“ orange”,“ ball”:[“ basketball”]}

并且如果呼叫没有该球的任何颜色: {“ 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 "\n";
    echo $ballcolor->getBall("black");

2 个答案:

答案 0 :(得分:0)

您应该使用

function __construct($ballcolor)

代替

function BallColor($ballcolor)

作为构造函数,除非您的php版本太旧。

答案 1 :(得分:0)

$this->ballcolor中获取所需的值后,再构建您需要返回的数组,然后进行json_encode:

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 "\n";
echo $ballcolor->getBall("black");

输出:

{"color":"orange","ball":["basketball"]} 
{"color":"black","ball":[]}