代码之家  ›  专栏  ›  技术社区  ›  Q_Mlilo

如何将JSON文本转换为PHP关联数组

  •  4
  • Q_Mlilo  · 技术社区  · 15 年前

    我将以下JSON对象存储在文本文件(data.txt)中:

    {"player":"black","time":"0","from":"2c","to":"3d"}
    

    我用php读到:

    <?php
      $data = file_get_contents('data.txt');
    ?>
    

    问题: 有什么简单的方法可以转换 $data 到一个PHP关联数组。我试过用 json_decode($data); 但那没用,有什么建议吗?

    3 回复  |  直到 15 年前
        1
  •  20
  •   VdesmedT    15 年前
    $assocArray = json_decode($data, true);
    

    第二个参数将结果设置为对象(false,默认值)或关联数组(true)。

        2
  •  2
  •   Horia Dragomir    15 年前

    尝试: json_decode($data, true)

    http://www.php.net/manual/en/function.json-decode.php

    这对我有效。另外,确保PHP版本具有json-encode/json-decode

        3
  •  0
  •   Chetan Sharma    11 年前

    您可以使用此函数在php中从json转换数组,这可以验证提供的字符串是否是有效的json:

    function convert_to_json($file, $in_array = True) {
        if(file_exists($file)) {
            $string = file_get_contents($file);
        }else {
            $string = $file;
        }
    
        $return_array = json_decode($string, $in_array);
        if (json_last_error() == JSON_ERROR_NONE) {
            return $return_array;
        }
    
        return False;
    }
    
    推荐文章