Welcome Guest, Not a member yet? Register   Sign In
JSON Output in a Specific Format.
#1

Hi,

I'm trying to work out how to output some data in JSON with this specific format:

      '{"rows":
         [
            {"Firstname": "John",
             "Lastname": "Smith"
            },
            {"Firstname": "Jane",
             "Lastname": "Doe"
            }
         ]
       }'


As an example, I've gotten close to what I need with something similar to this (except I don't need the index numbers)....

PHP Code:
      $name['firstname'] = 'John';
 
      $name['lastname'] = 'Smith'     
       $names
['1'] = $name;

 
      $name['firstname'] = 'Jane';
 
      $name['lastname'] = 'Doe'     
       $names
['2'] = $name 

      $this
->output
          
->set_content_type('application/json')
 
         ->set_output(json_encode($names)); 

....but it's not quite there:

'{"1":{"firstname":"John","lastname":"Smith"},"2":{"firstname":"Jane","lastname":"Doe"}}'

As you can see I need it to start with {"rows":[ and end with ]}.

Any guidance would much appreciated.

Thanks,

Steve

CodeIgniter 3.0.0
Reply
#2

You might try
Code:
$names[] = $name;
. That will add an array to $names without an index.
Reply
#3

(02-13-2017, 09:50 PM)ciadmin Wrote: You might try
Code:
$names[] = $name;
. That will add an array to $names without an index.

That's perfect.  Thank you!

All I have to do then is add the extra bits and I get the exact output I need:

PHP Code:
     $this->output
          
->set_content_type('application/json')
 
         ->set_output('{"rows":' json_encode($names) . '}'); 

Thank you again!

Steve
Reply




Theme © iAndrew 2016 - Forum software by © MyBB