title: Turning a CSV into a nested JSON object in PHP, Drupal 8
body: <p>I'm trying to turn a CSV into a JSON object made of nested arrays for each row within the file.</p>
  <p>I've tried a handful of similar SO questions but haven't found quite the right solution.</p>
  <p>I'm attempting to set up a JSON object with a handful of nested objects, based on the first value in each row of the CSV.</p>
  <p>My CSV file, titled data_source.csv looks like:</p>
  <pre><code>Organisation ID,Organisation Name,Postcode,Industry
  111,Organisation A,SW2 4DL,School
  123,Organisation B,S2 5PS,School
  234,Organisation C,EC2 3AD,School
  ...there are several more rows
  
  </code></pre>
  <p>My PHP code (in a controller in Drupal 8):</p>
  <pre><code>
  namespace Drupal\webform_autocomplete_csv\Controller;
  use Drupal\Core\Controller\ControllerBase;
  
  class WebformAutocompleteCsvController extends ControllerBase {
  
    public function content() {
  
      //make sure file can be accessed
  
      if (($handle = fopen('sites/default/files/data_source.csv', 'r')) === false) {
        die('Error opening file');
      }
  
      $organisation_id = fgetcsv($handle);
      
      //take the first value on each row
      array_shift($organisation_id);
  
      //create an array
      $data = array();
  
      while ($row = fgetcsv($handle)) {
        $key = array_shift($row);
        $data[$key] = array_combine($organisation_id, $row);
      }
  
      $json_object = json_encode($data);
  
      return $json_object;
  
    } //close content()
  
  }
  
  </code></pre>
  <p>The ideal situation would be a single JSON object with a series of nested objects, like:</p>
  <pre><code>Object {
    111 {
         Organisation Name:Organisation A,
         Postcode: SW2 4DL,
         Industry: School
    },
    123 {
         Organisation Name:Organisation b,
         Postcode: S2 5PS,
         Industry: School
    },
    234 {
         Organisation Name:Organisation C,
         Postcode: EC2 3AD,
         Industry: School
    }
  }
  
  </code></pre>
  <p>Is my PHP code set up as effectively as possible?</p>
  <p>When I run this on my local environment, I receive an error message that reads: 'LogicException: The controller must return a response ([the json object])'</p>
  <p>So my JSON object is included in the error message, which is encouraging but it's unclear why it's part of a LogicException.</p>