3

In PHP I am getting an array from foreach. I am JSON encoding and showing all the results at once. This works fine. But what if I need to display array items one by one as foreach still continues?

<?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

?>

SurvivalMachine
  • 7,946
  • 15
  • 57
  • 87

2 Answers2

0

Did you try http://www.php.net/array_shift ? its php function you need to call this function after 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.

?>

Thanks.

0

What you looking for is Streaming Response.

Checkout following link to learn how to do that.

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

Lost Koder
  • 864
  • 13
  • 32