阵列转向 json 使用 php

Array turn to json using php

需要你的帮助... 我正在尝试创建一个代码来获取 .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_arr as $key=>$value)
{
    $conents_arr[$key]  = rtrim($value, "\r");
}

$json_contents = json_encode($conents_arr, JSON_UNESCAPED_SLASHES);

echo $json_contents;
?>

当我试图回显 $json_contents

时,我已经得到了结果
["Sample Material 1","tRAINING|ENDING","01/25/2018 9:37:00 AM","639176882315,639176882859","Y,Y","~"]

但是当我尝试使用这种方法回显时$json_contents[0] 我只得到了每个字符的结果。

代码

结果

希望你能在这方面帮助我.. 谢谢

这是因为 $json_contents 是一个字符串。它可能是 json 字符串,但它是字符串,因此字符串属性将在此处应用,因此当您 echo $json_contents[0] 时,它会为您提供字符串的第一个字符。您可以将编码的 json 字符串解码为如下对象:

$json = json_decode($json_contents);
echo $json[0];

或在 json_encode:

之前回显
echo $conents_arr[0];
$json_contents = json_encode($conents_arr, JSON_UNESCAPED_SLASHES);

正如PHP.net所说 "Returns a string containing the JSON representation of the supplied value."

当您使用 $json_contents[0] 时,这将 return 作为 json 字符串的第一个字符。

你可以做到

$conents_arr[0]

或使用

将 json 字符串转换为 PHP 数组
$json_array = json_decode($json_contents, true);
echo $json_array[0];

json_encode() 函数将数组作为输入并将其转换为 json 字符串。

echo $json_contents; 打印字符串。

如果你想访问它,你必须解码 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];