I have a JSON array as formatted below, generated in PHP using a foreach loop to generate an array from an WP ACF group (see below). I seem to be unable to use GROUP BY when getting the particular fields for this ACF group, hence the double entry for name (with different times) as shown.
[
{"name":"Location1","gigs":
{"start":"16:30","end":"21:15","title":"TestTitle1","class":"fri"}
},
{"name":"Location 2","gigs":
{"start":"15:00","end":"19:00","title":"TestTitle2","class":"fri"}
},
{"name":"Location 1","gigs":
{"start":"21:00","end":"22:00","title":"TestTitle3","class":"fri"}
}
]
This JSON array should ideally be formatted as follows, the difference being the entries with the same name/location should be combined as shown below.
[
{
"name":"Location1",
"gigs": [
{"start":"16:30","end":"21:15","title":"TestTitle1","class":"fri"},
{"start":"21:00","end":"22:00","title":"TestTitle3","class":"fri"}
]
},
{
"name":"Location 2",
"gigs": [
{"start":"15:00","end":"19:00","title":"TestTitle2","class":"fri"}
]
}
]
I've tried several array merge/combine/sort/etc functions available in PHP, but can't get it to output as intended.
Here's the code generating the array/JSON output:
function get_shows( WP_REST_Request $request ) {
$parameters = $request->get_params();
switch($parameters[1]) {
case 'fri':
$show_day = 'fri';
$show_select_day = '20170901';
break;
case 'sat':
$show_day = 'sat';
$show_select_day = '20170902';
break;
case 'sun':
$show_day = 'sun';
$show_select_day = '20170903';
break;
}
$showDates = array();
$args = array(
'posts_per_page' => -1,
'post_type' => 'performances',
'meta_key' => 'per_date',
'meta_value' => $show_select_day
);
$shows = get_posts( $args );
if ( ! empty( $shows ) ) {
$i = 0;
foreach( $shows as $show ) {
$acf = get_fields($show->ID);
$show_loc = get_the_title(get_field('per_location',$show->ID));
$show_title = get_the_title(get_field('per_busker',$show->ID));
if ( ! empty( $acf ) ) {
$showDates[$i]['name'] = $show_loc;
$showDates[$i]['gigs']['start'] = date("H:i", strtotime($acf['per_time_start']));
$showDates[$i]['gigs']['end'] = date("H:i", strtotime($acf['per_time_end']));
$showDates[$i]['gigs']['title'] = $show_title;
$showDates[$i]['gigs']['class'] = $show_day;
}
$i++;
}
}
return $showDates;
}
Any suggestions to get the output in the correct format would be more than welcome. Thanks much!