我无法从json_decode数组中读取值

问题描述

我尝试通过wordpress中的json传递一些学生数据。数据取自csv文件,并且具有标题行和4行值。我使用发送数据到php JSON.stringify(inp)。 数据发送没有问题,我使用json_decode对其进行解码:$csvdata=json_decode(str_replace("\\","",$_POST['body2'])); -我使用str_replace(),因为没有它,数据无法正确读取-$csvdata没问题。我使用wp_send_json($csvdata);将其发送回我的页面,并且可以在控制台中看到我的数据。但是,当我尝试获取$csvdata的值时,无论尝试什么,都会得到3 null,null,null data的结果。

$i=0;
foreach($csvdata as $value) {
    $out[$i]=$value->student;
    $i++;
  }

wp_send_json($out); 它应该获取我的“学生”字段数据的值。我几乎尝试了所有操作,但没有结果。每次$out返回null,null,null

我也尝试$json_decode($_POST['body2'],true)将数据读取为数组而没有任何运气。还尝试了html_entity_decode()str_replace()的许多组合,但始终没有结果

任何建议?

[edit]我试图像这样手动重新创建我的csvdata:

$data2 =  json_decode('[{"student":"1","a1":"0"},{"student":"2","a1":"2"},{"student":"3",{"student":"4","a1":"3"}]');//works
$a=0;
foreach($data2 as $value) {
    $out1[$a]=$value->student;
    $a++;`
 }
    wp_send_json($out1);

现在可以正确读取值。我注意到,首先,当我在控制台日志中wp_send_json($ csvdata)出现时,每行的末尾都有额外的...(有圆点),这可能会引起问题,但我不知道该如何解决。 ..

{student: 1,a1: 0,a2: 0,a3: 0,a4: 0,…}

My data sent to php

console result of $csvdata

解决方法

经过3天的尝试,我发现错误是因为通过JSON我将元数据和数据一起传递了。因此,我需要将JSON.stringify(inp)替换为JSON.stringify(inp.data),然后一切正常。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...