1

I am using Codeigniter to fetch rows. Please go through the below code.

//Model

public function selectData() {
    $query = $this->db->query('SELECT * FROM tbl_favourites WHERE favourites_status = 1');
    $count = $query->num_rows();

    if($count > 0)
        return $result = $query->result_array();
    else
        return 0;
}

//Controller

$all_favourites = $this->select->selectData();

if(!empty($all_favourites)) {
    foreach($all_favourites as $favourites)
        echo json_encode($favourites);
}

From the above code, the output is

{"favourite_online_id":"3","favourite_online_url":"ddd","favourite_online_status":"0"}
{"favourite_online_id":"2","favourite_online_url":"http:\/\/www.google.com","favourite_online_status":"0"}

But I want the output to be formatted properly to satisfy the android JSON.

The required output is,

[
  {
    "favourite_online_id": "3",
    "favourite_online_url": "ddd",
    "favourite_online_status": "0"
  },
  {
    "favourite_online_id": "2",
    "favourite_online_url": "http://www.google.com",
    "favourite_online_status": "0"
  }
]
1
  • 4
    instead of encoding in foreach encode the main array. json_encode($all_favourites) Commented Nov 14, 2017 at 8:21

3 Answers 3

1

instead of using

if(!empty($all_favourites)) {
    foreach($all_favourites as $favourites)
        echo json_encode($favourites);
}

use directly

if(!empty($all_favourites)) {

        echo json_encode($all_favourites );
}
Sign up to request clarification or add additional context in comments.

Comments

1

I think you can modify your function

public function selectData() {
    $query = $this->db->query('SELECT * FROM tbl_favourites WHERE favourites_status = 1');
    $count = $query->num_rows();

    if($count > 0)
        return $result = $query->result_array();
    else
        return array();
}

//Controller

$all_favourites = $this->select->selectData();

// if(!empty($all_favourites)) {
//    foreach($all_favourites as $favourites)
//        echo json_encode($favourites);
// }
echo json_encode($all_favourites);

Comments

1

You can do in 2 way

1st way

if(!empty($all_favourites)) {
  echo json_encode($all_favourites);
}

2nd way

if you want to add something in that object then

$favouriteArray=[];
if(!empty($all_favourites)) {
    foreach($all_favourites as $favourites){
      array_push($favouriteArray, $favourites);
    }
}
echo json_encode($favouriteArray);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.