【问题标题】:Array turn to json using php数组使用php转json
【发布时间】:2018-04-02 04:02:24
【问题描述】:

在这方面需要您的帮助... 我正在尝试创建一个将获取 .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] 回显时 我只得到了每个字符的结果。

代码

结果

希望你能帮我解决这个问题.. 谢谢

【问题讨论】:

  • 你为什么要回复[0]?你想达到什么目的?

标签: php arrays json echo


【解决方案1】:

正如 PHP.net 所说 "返回一个 字符串,其中包含所提供值的 JSON 表示形式。"

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

你可以这样做

$conents_arr[0]

或者使用

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

【讨论】:

    【解决方案2】:

    这是因为$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);
    

    【讨论】:

      【解决方案3】:

      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];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-30
        • 2016-03-18
        • 2021-08-05
        • 2023-03-12
        • 2014-08-23
        • 2017-12-02
        相关资源
        最近更新 更多