在ajax中逐个显示foreach数组项


Display foreach array item one by one in ajax

在PHP中,我从foreach中获得一个数组。我是JSON编码和显示所有的结果一次。这很好。但是,如果我需要一个一个地显示数组项,因为foreach仍然在继续呢?

<?php 
$array = //somearray;
$data_arr = array();
foreach($array as $arr){
//do something
$data_arr[] = $arr;
}
echo json_encode(array('success'=>true,'data'=>$data_arr));
//here i can display the data in my jquery using each function
//i can display the whole data at once after the foreach is completed
//what i need is i want to display first element of data_arr after its loop is completed and then the second element and so on

?>

您试过http://www.php.net/array_shift吗?它是PHP函数你需要在foreach

之后调用这个函数
<?php 
foreach($array as $arr){
//do something
$data_arr[] = $arr;
}
print_r array_shift($data_arr);
//Print First array value from this $data_arr list.
?>

谢谢。

您要找的是Streaming Response

查看下面的链接,了解如何做到这一点。

https://www.sitepoint.com/php-streaming-output-buffering-explained/