Php json_解码返回1的数组

Php json_解码返回1的数组,php,json,jsonp,Php,Json,Jsonp,我试图将一些JSON解码成php数组。以下是代码摘录: $getfile="{"fname":"bob","lname":"thomas","cascade":"bthomas","loc":"res","place":"home 2"}"; $arr = json_decode($getfile, true); $arr['day3'] = $selecter; echo(print_r($arr)); 唯一返回的是“1”。我已经检查了JSONLint,它是有效的json,所以我想知道为什么

我试图将一些JSON解码成php数组。以下是代码摘录:

$getfile="{"fname":"bob","lname":"thomas","cascade":"bthomas","loc":"res","place":"home 2"}";
$arr = json_decode($getfile, true);
$arr['day3'] = $selecter;
echo(print_r($arr));
唯一返回的是“1”。我已经检查了JSONLint,它是有效的json,所以我想知道为什么json_解码失败了。在向数组添加day3键之前,我还尝试检查数组是什么,但仍然返回“1”。感谢您的帮助

实际代码:

$getfile = "";
    $getfile = file_get_contents($file);
    if ($getfile == "") {
        writeLog("Error reading file.");
    }
    writeLog("getfile is " . $getfile);
    writeLog("Decoding JSON data");
    $arr = json_decode($getfile, true);
    writeLog("Decoded raw: " . print_r($arr));
    writeLog("Editing raw data. Adding data for day " . $day);
    $arr['day3'] = $selecter;
    writeLog(print_r($arr));
    $newfile = json_enconde($arr);
    writeLog($newfile);
    if (file_put_contents($file, $newfile)) {
        writeLog("Wrote file to " . $file);
        echo $newfile;
    } else {
        writeLog("Error writting file");
    }
这些是$file的内容(它是一个文本文件)

我们仍然不知道你的档案里有什么。但是,如果:

"{"fname":"bob","lname":"thomas","cascade":"bthomas","loc":"res","place":"home 2"}"
然后,多余的外部双引号将使JSON出错,并返回NULL。用来找出答案。也可能是UTF-8 BOM或其他东西

无论如何,
1
是来自的结果。直接打印输出,不需要回显。也用于调试而不是使用


更具体地说,您希望返回
打印\r
输出(而不是布尔成功结果
1
),然后将其写入日志

因此,请使用:

      writeLog(print_r($arr, TRUE));

请注意
TRUE
参数。

首先,使用单引号。这将导致分析错误

$getfile= '{"fname":"bob","lname":"thomas","cascade":"bthomas","loc":"res","place":"home 2"}';
我假设您已经声明了$selector,并且它已被分配到某个值

从echo(打印($arr))中删除echo您不需要echo。打印\u r也将输出。如果使用echo,它将在数组末尾显示1

工作守则:

$getfile = '{"fname":"bob","lname":"thomas","cascade":"bthomas","loc":"res","place":"home 2"}';
    $arr = json_decode($getfile, true);
    $selecter = 'foobar';
    $arr['day3'] = $selecter;
    print_r($arr);

希望这有帮助。

我这样做时遇到了这个问题:

if ($arr = json_decode($getfile, true)) {
    $arr['day3'] = $selecter;
    echo(print_r($arr));
}

在if之外解码是解决方案。

你能发布你的实际代码吗?我希望出现解析错误,而不是
1
。尝试在JSON字符串的末尾加上单引号。@mario他看到
1
,因为嵌套的
echo(print_r())
print_r()
调用返回
bool(true)
,当
echo
ed导致
1
。不过,您仍然希望看到阵列输出。。。编辑哦,如果
json_decode()
返回
NULL
(也可能是
FALSE
,我不确定,我必须检查)不是$getfile=“”,它实际上会这样工作;当文件获取内容时,将JSON设置为字符串?@Vikram the
$getfile=“”是冗余的,可以删除,重新分配时,变量的当前类型不会影响新类型。
if ($arr = json_decode($getfile, true)) {
    $arr['day3'] = $selecter;
    echo(print_r($arr));
}