I want to get a JSON object like [{"Video link": "",....},...]
from form entries with "labels". Now I am using this code
$form_id = '1';
$form = GFAPI::get_form( $form_id );
$labels = [];
foreach ($form['fields'] as $key => $value) {
$labels[$value['id']] = $value['label'];
}
$data = [];
$i = 0;
$entries = GFAPI::get_entries($form_id);
foreach ($entries as $entry) {
foreach ($entry as $key => $value) {
if(isset($labels[$key])){
$data[$i][$labels[$key]] = $value;
}else{
$data[$i][$key] = $value;
}
}
$i++;
}
echo '<script>const data = '.json_encode($data).'</script>';
The problem is with custom fields label names like ["id"]=> int(11) ["label"]=> string(10) "Video link"
. So I have to put them in $labels array like [11]=>"Video link" and then run through 2 loops with $entries to create a new array $data.
Is there any simple way to do this?
I want to get a JSON object like [{"Video link": "https://www.youtube/watch?v=r",....},...]
from form entries with "labels". Now I am using this code
$form_id = '1';
$form = GFAPI::get_form( $form_id );
$labels = [];
foreach ($form['fields'] as $key => $value) {
$labels[$value['id']] = $value['label'];
}
$data = [];
$i = 0;
$entries = GFAPI::get_entries($form_id);
foreach ($entries as $entry) {
foreach ($entry as $key => $value) {
if(isset($labels[$key])){
$data[$i][$labels[$key]] = $value;
}else{
$data[$i][$key] = $value;
}
}
$i++;
}
echo '<script>const data = '.json_encode($data).'</script>';
The problem is with custom fields label names like ["id"]=> int(11) ["label"]=> string(10) "Video link"
. So I have to put them in $labels array like [11]=>"Video link" and then run through 2 loops with $entries to create a new array $data.
Is there any simple way to do this?
- 1 To clarify, does the above code work and you are looking to simplify or does the above code not work as you want? If the latter, could you elaborate on how it is not working? – Dave from Gravity Wiz Commented Apr 22, 2020 at 11:27
- @DavefromGravityWiz the code is working, but I think there is a simple way to do this – SERG Commented Apr 23, 2020 at 6:53
1 Answer
Reset to default 2I'm not sure there is much that can be done to truly simplify this... you certainly have the right idea on what needs to be done. Here's one take you might consider that simplifies it a bit by removing not prefetching the labels. This simpler version is negligibly less performant.
$form_id = '1';
$form = GFAPI::get_form( $form_id );
$entries = GFAPI::get_entries( $form_id );
$data = [];
foreach ( $entries as $index => $entry ) {
foreach ( $entry as $key => $value ) {
$field = GFAPI::get_field( $form, $key );
$label = $field ? $field->get_field_label( false, '' ) : $key;
$data[ $i ][ $label ] = $value;
}
$i++;
}
echo '<script>const data = ' . json_encode( $data ) . '</script>';