【问题标题】:Convert PHP string to JSON array将 PHP 字符串转换为 JSON 数组
【发布时间】:2013-11-20 09:32:27
【问题描述】:

问题:

将 PHP 字符串转换为 JSON 数组。

我在 PHP 中有一个如下所示的字符串:

intelligence skin weight volume

期望的输出:

在 PHP 中有没有一种方法可以转换它,所以它看起来像这样:

["skin", "intelligence", "weight", "volume"]

我查看了 json_encode(),但它只在关键字周围加上了双引号。

【问题讨论】:

    标签: php jquery arrays json


    【解决方案1】:

    如果你想创建 JSON 数组,你必须先将你的输入字符串分解成一个数组。

    尝试:

    $input  = 'intelligence skin weight volume';
    $output = json_encode(explode(' ', $input));
    

    【讨论】:

      【解决方案2】:

      首先根据空格分解字符串。然后你得到一个包含单个单词的数组。然后 json_encode 数组

      $string="intelligence skin weight volume";
      $array=explode(' ',$string);
      $json=json_encode($array);
      

      【讨论】:

        【解决方案3】:

        查看json_encode

        此函数需要数组并将数组转换为 json。然后使用json_decode() 将 json 还原为数组

        【讨论】:

          【解决方案4】:
          $str="intelligence skin weight volume";
          $arr=explode(' ',$str);
          $json=json_encode($arr);
          

          explode() 用于通过分隔符分割字符串(在这个场景中它是“”)现在您可以将返回数组编码为 json。

          【讨论】:

            【解决方案5】:

            使用 json_encode

            $jsonVal = json_encode(explode(' ', "intelligence skin weight volume"));
            

            【讨论】:

              猜你喜欢
              • 2016-04-28
              • 1970-01-01
              • 2014-07-11
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多