php循环并存储到数组中

php for loop and storing in to arrays

本文关键字:数组 存储 循环 php      更新时间:2023-09-26

我正试图通过ajax请求将一些值从javascript传递到php文件,并使用php将每个结果(来自for循环)存储到数组中。

queryData={"data":{"data_string":{"data":"medicine","default_field":"Content"}}}
testArgument=0;
$.ajax({
    url:"test/queryManipulate.php",
    type: 'POST',
    datatype: 'json',
    data: {field : queryData, start : testArgument},
    success:function(jsonQuery)
    {
       alert(jsonQuery);
    }
});

<?php
    $i=0;
for ($from = 0; $from <= 50; $from+=10)
{
$object=json_decode($_POST["field"]); 
$object->from=$from; 
$object=json_encode($object);
$ch = curl_init("http://localhost:9200/algotree//_search");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $object);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$test= curl_exec($ch);
curl_close ($ch);
$newArray[$i]= $test;
$i++;
echo $newArray[2];
}
?>

MY for循环不起作用。我使用它的方式正确吗?我如何将每个结果存储到php中的数组中?

第一个循环应该是

    <?php
        for($from = $_POST["start"]; $from<50;$from+=10)
        {
             // other code
        }

注意$from+=10,而不是$from+10。

在javascript中,在转换为json字符串之前,我们必须使用数组和对象(如)格式化数据

data_string  = new Object();
data = new Array();
data_string[data] = "medicine";
data_string[default_field] = "Content";
data.push(data_string);

然后将数据编码为json,结果会像一样

{"data":{"data_string":{"data":"medicine","default_field":"Content"}}}

然后通过ajax传递到php文件,然后使用解码json

php 中的json_encode(data);

然后做进一步的处理。。