【问题标题】:Split JSON data and only get the variables names拆分 JSON 数据并仅获取变量名称
【发布时间】:2016-03-29 11:20:00
【问题描述】:

我正在制作一个 CMS,您必须在其中放入自己的 JSON 数据字符串。 Like this

然后它会转到一个 php 文件。但是在那个文件中我想拆分数据字符串

来自这样的事情:

 {"main_object": {"audio":"nl", "title":"Opdracht 1", "vraag":"[0, 1, "a"]", "antwoord"["yes", "no", 0]" }}

到这里

["audio", "title", "vraag", "antwoord"]

【问题讨论】:

    标签: php json forms http-post


    【解决方案1】:

    使用 json_decode,小心,您的 JSON 字符串不正确:

    $json_string = '{"main_object": {"audio":"nl", "title":"Opdracht 1", "vraag":[0, 1, "a"], "antwoord":["yes", "no", 0]}}';
    
    // Add TRUE to force an array, not an object
    $array = json_decode($json_string, TRUE);
    print_r(array_keys($array['main_object']));
    

    它适用于此代码。我试过了。

    【讨论】:

    • 如果我这样做,我会得到“解析错误:语法错误,意外';' "
    • 是的,我忘了分号。试试我的新代码。顺便说一句,您的 JSON 格式不正确。
    【解决方案2】:

    假设以下 PHP 代码:

     <?php
     $JSONData = '{"main_object": {"audio":"nl", "title":"Opdracht 1", "vraag":"[0, 1, "a"]", "antwoord"["yes", "no", 0]" }}'; //In reality you'll be getting the JSON data from the form rather than assigning it here.
    
      $arrayData = json_decode($JSONData, true);
      if ($arrayData !== null 
          && is_array($arrayData)
          && isset($arrayData["main_object"])
          && is_array($arrayData["main_object"])) { //JSON was valid and in the correct format
          $usableData = array_keys($arrayData["main_object"]);
          //Do whatever you need to do with your $usableData
      } else {
         //Handle badly formatted data here.
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-22
      • 1970-01-01
      • 2015-09-15
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多