-1

I need to sort the multidimensional array with output by value. I can not group the nested arrays by date and output it with the title (date). There is an array:

Array ( 
[0] => ( 
[ID] => 959 
[title] => title 
[post_date] => 2018-01-01 10:17:49 
    )
[1] => ( 
[ID] => 960 
[title] => title 
[post_date] => 2018-01-01 10:17:49 
    )
[2] => ( 
[ID] => 961 
[title] => title 
[post_date] => 2018-01-02 10:17:49 
    )
[3] => ( 
[ID] => 962 
[title] => title 
[post_date] => 2014-01-02 10:17:49 
    )
[4] => ( 
[ID] => 963 
[title] => title 
[post_date] => 2014-01-03 10:17:49 
    )      
)

As a result, I need to get this. There is a date as the header and all arrays in which this date.

Result

- 2018-01-01 -

id: 959 Title
id: 560 Title

- 2018-01-02 -

id: 961 Title
id: 562 Title

- 2018-01-02 -

id: 963 Title

.....
picciano
  • 22,341
  • 9
  • 69
  • 82
RQEST
  • 107
  • 1
  • 9
  • You want output as an array? – Alive to die - Anant Jan 25 '18 at 20:31
  • It is necessary to display the Date, for example - 2018-01-01 - (as the header), and line by line to display all the data from the masivs in which this date. – RQEST Jan 25 '18 at 20:34
  • The thing is, I already did it before, but now I just can not remember how it was. Even Google did not help me remember. – RQEST Jan 25 '18 at 20:38
  • [Sort the array](https://stackoverflow.com/a/17364128/476), iterate it, remembering the last headline you output, when the date of the current entry is different than the last output headline, output a headline. – deceze Jan 25 '18 at 20:45

2 Answers2

1

have you done with part about sorting? I assume you are. So the only thing left is "grouping".

But actually you don't need to group data. Just iterate sorted items one by one and remember date from previous element. Once dates for current element and for previous one differ - you output "header". Something like that:

$data = [[a=> 2, b=> 1], [a=> 2, b=> 4], [a=> 3, b=> 1], [a=> 4, b=> 0]];
$previous_a = null;
foreach($data as $item) {
    if ($item['a'] != $previous_a) {
         echo 'header --- '.$item['a'].'<br />';
    }
    $previous_a = $item['a'];
    echo $item['b'].'<br />';
}
skyboyer
  • 22,209
  • 7
  • 57
  • 64
0

You could try something like this :

$aggreg = [] ;
foreach ($array as $item) {
    $day = $item['post_date'];
    // if you want to group by day, just use $day = substr($day,0,10) ;
    $aggreg[$day][] = 'id: ' . $item['ID'] . " " . $item['title'] ;
} 

krsort($aggreg) ; // or ksort() or just comment this line.

// then build the output :

$output = "" ;
foreach ($aggreg as $day => $data) {
    $output .= "- " .substr($day,0,10) . " -\n\n" . implode("\n", $data) . "\n\n" ;
}

print $output ;

Will outputs :

- 2018-01-02 -

id: 961 title

- 2018-01-01 -

id: 959 title
id: 960 title

- 2014-01-03 -

id: 963 title

- 2014-01-02 -

id: 962 title

NB If you have to output this in HTML, please change \n to <br>

Syscall
  • 19,327
  • 10
  • 37
  • 52