我正在使用数组处理 JavaScript 和 PHP,第一步是在此处创建数组
var ListaA=[];
var i = 0, len = options.length;
while (i < len){
var tmp = {
'proyecto':'test',
'pendientes1':0,
'pendientes2':0,
'terminadas1':0,
'terminadas2':0,
'solucion':0
};
ListaA.push(tmp);
i++;
}
然后我像这样将它发送到我的 PHP 文件
var laLista = JSON.stringify(ListaA);
$.get("php/operation.php?test="+ {'test' : laLista }, function( data ){
var tmp = {
'proyecto':""+value['proyecto']+"",
'pendientes1':""+value['pendientes1']+"",
'pendientes2':""+value['pendientes2']+"",
'terminadas1':""+value['terminadas1']+"",
'terminadas2':""+value['terminadas2']+"",
'solucion':""+value['solucion']+""
};
ListaA.push(tmp);
});
正如您在上面看到的,我已经准备好代码来获取代表 PHP 文件发送的数组的数据,所以我已经涵盖了那部分,我的问题在我的 PHP 文件中,在这里。
$arrayWork = json_decode($_POST['test']);
然后我想循环,这一次,只是为了测试我只是采用其中一个值并增加它来观察结果,就像这样
foreach($arrayWork as $value){
$value['pendientes1']++; // this is not working for me
}
我得到以下信息:“foreach 中提供的参数无效”。那么,我的代码有什么问题?哪个是循环它并将其返回给我的 JavaScript 的正确方法?
我希望你能帮我解决这个问题。感谢您的时间和关注,晚安。
最佳答案
使用这段代码
$arrayWork = json_decode($_POST['test']);
你的json并没有真正转化成关联数组,看下面
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
assoc When TRUE, returned objects will be converted into associative arrays.
要将 json 对象转换为数组,只需将 true
添加到它的第二个参数即可
$arrayWork = json_decode($_POST['test'], true);**strong text**
增加数组中的索引值
foreach($arrayWork $key => as $value){
$arrayWork['pendientes1']++;
}
已编辑。
同样,因为您正在使用 $_POST
方法,请将您的 ajax 从 $.get
更改为 $.post
$.post("php/operation.php?test="+ {'test' : laLista }, function( data ){
var result = JSON.parse(data); // parse json string into json object
...
});
关于javascript - 循环数组以修改值(JavaScript 到 PHP 并返回到 JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41275982/