Search code examples
javascriptphpmaterialize

Convert PHP array into JSON object for autocomplete


I am using the MaterializeCSS autocomplete and would like to use one of my PHP arrays to output all of the possible options into a form. Please see below for the current code.

  const ac = document.querySelector('.autocomplete');
  M.Autocomplete.init(ac, {
    data: {
      "Test1": null,
      "Test2": null,
      "Test3": null
    },
  });

I would very much like to use a simple $keysArray in order to input the Test1, Test2, Test3 options etc. However, I understand from the MaterializeCSS page that the autocomplete is using an object and not an array. As such, I have attempted to convert my $keysArray into an object using various different methods:

  <?php
  $keysArray = array (
    "Test1",
    "Test2",
    "Test3"
  );
  ?>

  var tempArray = <?php echo json_decode(json_encode($keysArray)); ?>; // Doesn't work
  var tempArray = <?php echo json_decode(json_encode($keysArray, JSON_FORCE_OBJECT)); ?>; // Also doesn't work

  const ac = document.querySelector('.autocomplete');
  M.Autocomplete.init(ac, {
    data: tempArray;
  });

None of the tempArray's work. I would very much appreciate if anyone can help me sort out what I am doing wrong.


Solution

  • Convert your array into similar key-value structure:

      $keysArray = array(
        "Test1" => null,
        "Test2" => null,
        "Test3" => null,
      );
      echo json_encode($keysArray); // {"Test1":null,"Test2":null,"Test3":null}
    

    It can be converted with:

    $array = array('Test1', 'Test2', 'Test3');
    $keysArray = array_combine($array, array_fill(0, count($array), null));