Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在php中正确地将数组返回到ajax调用?_Php_Arrays_Json - Fatal编程技术网

如何在php中正确地将数组返回到ajax调用?

如何在php中正确地将数组返回到ajax调用?,php,arrays,json,Php,Arrays,Json,ajax在php下面调用,并期望返回一个json数组。我想我已经准备好了数据,但不知道如何正确返回它们 $files = array(); foreach($db2_databaselist as $db) { $file = new stdClass(); $file->data = date('Y-m-d--H:i:s',strtotime($db)); $file->attr = new stdClass(); $file->attr-&

ajax在php下面调用,并期望返回一个json数组。我想我已经准备好了数据,但不知道如何正确返回它们

$files = array();
foreach($db2_databaselist as $db) {

    $file = new stdClass();
    $file->data = date('Y-m-d--H:i:s',strtotime($db));
    $file->attr = new stdClass();
    $file->attr->rel = "file";
    $file->attr->timestamp = $db.$type[0];

    $files[] = json_encode($file);
}
   echo "<pre>Output = " . print_r($files,TRUE) . "</pre>";
   echo "<BR><BR><BR>";
   print_r($files, TRUE);
但是
print\r($files,TRUE)
不返回任何内容

如何让php返回

echo '['.implode(',',$files).']';

循环之后不需要json编码。需要。您的数组值已经是JSON字符串,这意味着使用JSON_encode只会转义字符串

相反:

$files[] = json_encode($file);
或者!您可以跳过这一行的json_编码:

    $files[] = $file;
}

$files = json_encode( $files );
而循环的结尾看起来是这样的:

print json_encode($files);

循环之后不需要json编码。需要。您的数组值已经是JSON字符串,这意味着使用JSON_encode只会转义字符串

相反:

$files[] = json_encode($file);
或者!您可以跳过这一行的json_编码:

    $files[] = $file;
}

$files = json_encode( $files );
而循环的结尾看起来是这样的:

print json_encode($files);

您需要使用
json\u encode
php函数


您需要使用
json\u encode
php函数


echo-json\u-encode($files)
应该足够了

echo-json\u-encode($files)
应该足够了

我更喜欢第二种解决方案。太好了,你发现了它。@Radek我在第一次搜索中没有看到json_编码,我这样做是因为我不知道如何使
$files
成为一个对象,所以我只能使用对象。所以我制作了一个数组。现在一切都很顺利。我更喜欢第二种解决方案。太好了,你发现了它。@Radek我在第一次搜索中没有看到json_编码,我这样做是因为我不知道如何使
$files
成为一个对象,所以我只能使用对象。所以我制作了一个数组。现在工作很顺利。