JSON Formatting the ouput of $option value for Drop down select?

815 Views Asked by At

This is a newbie question... I have a form in Joomla 3.3 and chronoforms v5 latest... When the form loads the database populates my first select input with "interview dates" from my DB.... works great, once you select the date, the second select input populates with available time slots.... the problem here is the way the DB is output in the array is

Data-> time->7:00am,7:15am,9:30am

Right now when the 2nd select loads it's showing up like this 7:00am,7:15am,9:30am.... I want to be able to make them individual values not all one value... This is the code I am currently using for the "time" options for the second select input...

    <?php
    $options = array();
    if ( !$form->data['Data'] || count($form->data['Data']) < 1 ) {
      // no result was found
      $options[] = 'Please select a category';
    } else {
      foreach ( $form->data['Data'] as $d ) {
        $options[$d['interviewdate']] = ($d['time']);
      }
    }
    echo json_encode ($options);
    ?>

is this possible?

2

There are 2 best solutions below

9
Tezd On

If i am not mistaken your $d['time'] holds values like '7:00am,7:15am,9:30am'. And if this is the case then you can just use explode(',', $d['time']) which will give you array of times instead of string.

$options = array();
$form = new stdClass();
$form->data['Data'] = array(
    array(
        'interviewdate' => 'date', 'time' => '7:02am,7:25am,9:40am'
    ),
    array(
        'interviewdate' => 'date2', 'time' => '7:05am,7:35am,19:40am'
    )
);
if ( !$form->data['Data'] || count($form->data['Data']) < 1 ) {
    // no result was found
    $options[] = 'Please select a category';
} else {
    foreach ( $form->data['Data'] as $d ) {
       foreach(explode(',', $d['time']) as $time){
          $options[] = array($d['interviewdate'] => $time);
       }
    }
}
echo json_encode ($options);
0
GreyHead On

The structure that is needed to create an options list is like this:

[0] => array ('text' => 'aaa', 'value' => 'xxx'),
[1] => array ( . . .

And your data appears to be be in a nested array like $form->data['Data']['time'] ?

In this case the text and value can probably be the same so the code would be something like this:

<?php
$options = array();
if ( !$form->data['Data']['time'] ) {
  // no result was found
  $options[] = array('text' => 'Please select a category', 'value' => '');
} else {
  $data = explode(',', $form->data['Data']['time']);
  foreach ( $data as $d ) {
    $options[] = array('text' => $d['time'], 'value' => $d['time']);
  }
}
echo json_encode($options);
?>