3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php $listOfPosts = [ [ 'date' => '2017-06-01', 'id' => 1, ], [ 'date' => '2017-06-01', 'id' => 2, ], [ 'date' => '2017-06-01', 'id' => 3, ], [ 'date' => '2017-06-02', 'id' => 4, ], [ 'date' => '2017-06-03', 'id' => 5, ], [ 'date' => '2017-06-04', 'id' => 6, ], ]; $listOfPostsPage2 = [ [ 'date' => '2017-06-05', 'id' => 1, ], [ 'date' => '2017-06-06', 'id' => 2, ], [ 'date' => '2017-06-07', 'id' => 3, ], [ 'date' => '2017-06-08', 'id' => 4, ] ]; $amountOfDays = 6; $newPostsArr = []; foreach($listOfPosts as $tmp) { if (count($newPostsArr) === $amountOfDays) { var_dump('All days added'); // We are done. break; } $newPostsArr[$tmp['date']][] = $tmp; } // Or like this function iteratePosts($pages, $newPosts) { foreach($pages as $tmp) { $newPosts[$tmp['date']][] = $tmp; } return $newPosts; } $newPostsArr = iteratePosts($listOfPosts, $newPostsArr); if (count($newPostsArr) < $amountOfDays) { // Fetch new page, keep adding entries var_dump('iterating again..'); $newPostsArr = iteratePosts($listOfPostsPage2, $newPostsArr); } var_dump($newPostsArr);
Output for 5.6.0 - 5.6.30, hhvm-3.15.4, 7.0.0 - 7.3.0alpha1
string(17) "iterating again.." array(8) { ["2017-06-01"]=> array(6) { [0]=> array(2) { ["date"]=> string(10) "2017-06-01" ["id"]=> int(1) } [1]=> array(2) { ["date"]=> string(10) "2017-06-01" ["id"]=> int(2) } [2]=> array(2) { ["date"]=> string(10) "2017-06-01" ["id"]=> int(3) } [3]=> array(2) { ["date"]=> string(10) "2017-06-01" ["id"]=> int(1) } [4]=> array(2) { ["date"]=> string(10) "2017-06-01" ["id"]=> int(2) } [5]=> array(2) { ["date"]=> string(10) "2017-06-01" ["id"]=> int(3) } } ["2017-06-02"]=> array(2) { [0]=> array(2) { ["date"]=> string(10) "2017-06-02" ["id"]=> int(4) } [1]=> array(2) { ["date"]=> string(10) "2017-06-02" ["id"]=> int(4) } } ["2017-06-03"]=> array(2) { [0]=> array(2) { ["date"]=> string(10) "2017-06-03" ["id"]=> int(5) } [1]=> array(2) { ["date"]=> string(10) "2017-06-03" ["id"]=> int(5) } } ["2017-06-04"]=> array(2) { [0]=> array(2) { ["date"]=> string(10) "2017-06-04" ["id"]=> int(6) } [1]=> array(2) { ["date"]=> string(10) "2017-06-04" ["id"]=> int(6) } } ["2017-06-05"]=> array(1) { [0]=> array(2) { ["date"]=> string(10) "2017-06-05" ["id"]=> int(1) } } ["2017-06-06"]=> array(1) { [0]=> array(2) { ["date"]=> string(10) "2017-06-06" ["id"]=> int(2) } } ["2017-06-07"]=> array(1) { [0]=> array(2) { ["date"]=> string(10) "2017-06-07" ["id"]=> int(3) } } ["2017-06-08"]=> array(1) { [0]=> array(2) { ["date"]=> string(10) "2017-06-08" ["id"]=> int(4) } } }