Nishan Singha Nishan Singha - 21 days ago 9
PHP Question

Getting json data from active record

I want to make json data from my query. But i can't get my json data as i am expected. Please help. Here is the code i tried. (its looks like your post is mostly code; please add some more details. is this enough?)

<?php
$this->db->select('campus.*, class.*');
$this->db->from('campus');
$this->db->join('class', 'campus.id = class.campus_id');
$campus_info = $this->db->get()->result_array();
foreach ($campus_info as $row) {
$var[]['id'] = $row['id'];
$var[]['campus_name'] = $row['campus_name'];
$var[]['class_id'] = $row['class_id'];
$var[]['class_name'] = $row['name'];
}
$json_data = json_encode($var, JSON_PRETTY_PRINT);
echo '<pre>';
echo $json_data;
echo '</pre>';
exit();


My query result is

Array
(
[0] => Array
(
[id] => 4
[campus_name] => Test Campus Name
[institute_name] => Test Institute Name 1
[class_id] => 11
[name] => STD - VIII
[campus_id] => 4
[name_numeric] => 8
[teacher_id] => 6
)

[1] => Array
(
[id] => 4
[campus_name] => Test Campus Name
[institute_name] => Test Institute Name 1
[class_id] => 15
[name] => A' Level
[campus_id] => 4
[name_numeric] => 12
[teacher_id] => 6
)


wanted to make it json like

[{
"id": "7",
"campus_name": "Azimpur",
"class_id": "9",
"class_name": "STD - VI"
}
{
"id": "8",
"campus_name": "Azimpur",
"class_id": "10",
"class_name": "STD - VII"
}]


But get

[
{
"id": "4"
},
{
"campus_name": "Test Campus Name"
},
{
"class_id": "11"
},
{
"class_name": "STD - VIII"
},
{
"id": "4"
},
{
"campus_name": "Test Campus Name"
},

Answer

This is your problem:

foreach ($campus_info as $row) {
  $var[]['id'] = $row['id'];
  $var[]['campus_name'] = $row['campus_name'];
  $var[]['class_id'] = $row['class_id'];          
  $var[]['class_name'] = $row['name'];
}

Here you are adding 4 elements to the hightest level of your $var variable.

You should only add one element:

foreach ($campus_info as $row) {
  $var[] = [
    'id' => $row['id'],
    'campus_name' => $row['campus_name'],
    'class_id' => $row['class_id'],     
    'class_name' => $row['name']
  ];
}

If you only select the columns you need, you can reduce this to:

foreach ($campus_info as $row) {
  $var[] = $row;
}

And perhaps even further if your database api has a fetchAll method.