使用php将数组转换为json
在这件事上需要你的帮助。。。 我正在尝试创建一个代码,该代码将获得一个.txt文件,并将所有文本内容转换为json 以下是我的示例代码:使用php将数组转换为json,php,arrays,json,echo,Php,Arrays,Json,Echo,在这件事上需要你的帮助。。。 我正在尝试创建一个代码,该代码将获得一个.txt文件,并将所有文本内容转换为json 以下是我的示例代码: <?php // make your required checks $fp = 'SampleMessage01.txt'; // get the contents of file in array $conents_arr = file($fp, FILE_IGNORE_NEW_LINES); foreach($conents_ar
<?php
// make your required checks
$fp = 'SampleMessage01.txt';
// get the contents of file in array
$conents_arr = file($fp, FILE_IGNORE_NEW_LINES);
foreach($conents_arr as $key=>$value)
{
$conents_arr[$key] = rtrim($value, "\r");
}
$json_contents = json_encode($conents_arr, JSON_UNESCAPED_SLASHES);
echo $json_contents;
?>
但是当我尝试使用类似于此的方法进行回显时,$json\u contents[0]
我只得到了每个字符的结果
代码
结果
希望你能在这件事上帮我。。
谢谢这是因为
$json\u contents
是一个字符串。它可能是json字符串,但它是字符串,因此字符串属性将应用于此处,因此当您echo$json\u contents[0]
时,它将为您提供字符串的第一个字符。您可以将编码的json字符串解码为如下所示的对象:
$json = json_decode($json_contents);
echo $json[0];
或者在json\u编码之前回显:
echo $conents_arr[0];
$json_contents = json_encode($conents_arr, JSON_UNESCAPED_SLASHES);
之所以发生这种情况,是因为$json\u contents
是一个字符串。它可能是json字符串,但它是字符串,因此字符串属性将应用于此处,因此当您echo$json\u contents[0]
时,它将为您提供字符串的第一个字符。您可以将编码的json字符串解码为如下所示的对象:
$json = json_decode($json_contents);
echo $json[0];
或者在json\u编码之前回显:
echo $conents_arr[0];
$json_contents = json_encode($conents_arr, JSON_UNESCAPED_SLASHES);
正如PHP.net所说
“返回包含所提供值的JSON表示形式的字符串。”
当您使用$json_contents[0]时,这将返回json字符串的第一个字符
你可以这样做
$conents_arr[0]
或者使用
$json_array = json_decode($json_contents, true);
echo $json_array[0];
正如PHP.net所说
“返回包含所提供值的JSON表示形式的字符串。”
当您使用$json_contents[0]时,这将返回json字符串的第一个字符
你可以这样做
$conents_arr[0]
或者使用
$json_array = json_decode($json_contents, true);
echo $json_array[0];
json_encode()函数将数组作为输入,并将其转换为json字符串
echo$json\u内容代码>只需打印出字符串
如果您想访问它,您必须将JSON字符串解码到数组中
//this convert array to json string
$json_contents = json_encode($conents_arr, JSON_UNESCAPED_SLASHES);
//this convert json string to an array.
$json_contents = json_decode($json_contents, true);
//now you can access it
echo $json_contents[0];
json_encode()函数将数组作为输入,并将其转换为json字符串
echo$json\u内容代码>只需打印出字符串
如果您想访问它,您必须将JSON字符串解码到数组中
//this convert array to json string
$json_contents = json_encode($conents_arr, JSON_UNESCAPED_SLASHES);
//this convert json string to an array.
$json_contents = json_decode($json_contents, true);
//now you can access it
echo $json_contents[0];
你为什么回显[0]
?你想达到什么目的?你为什么回应[0]
?你想达到什么目标?