0

i've problem convert query to json encode

This is the code:

$list = $this->M_Bio->dataBio();
$data = array();
foreach ($list as $result) {
$row = array();
$row[] = ['name' => $result->fullname];
$row[] = ['position' => $result->position];
$row[] = ['office' => $result->office];
$row[] = ['extn' => $result->phone];
$data[] = $row;
}
$output = array(
"data" => $data,
);
echo json_encode($output);

Result json encode:

{"data": [
["name": "Tiger Nixon","position": "System Architect","office": "Edinburgh","extn": "5421"],["name": "Cedric Kelly","position": "Senior Javascript Developer", "office": "Edinburgh","extn": "6224"]
    ]
}

I want the results like this:

    {
    "data": [
    {
    "name": "Tiger Nixon",
    "position": "System Architect",
    "office": "Edinburgh",
    "extn": "5421"
    },
    {
    "name": "Cedric Kelly",
    "position": "Senior Javascript Developer",
    "office": "Edinburgh",
    "extn": "6224"
    }
    ]
    }

What should i do? please help me

1
  • 1
    You have shown invalid json Result json encode: . JSON can not have key:value pairs in []; Commented Sep 1, 2018 at 18:42

1 Answer 1

2

You need to change the way you add all of the data into the $output array...

$row = array();
$row['name'] = $result->fullname;
$row['position'] = $result->position;
$row['office'] = $result->office;
$row['extn'] =$result->phone;
$data[] = $row;

This will give you a cleaner result in the output array.

You could build them all in one go...

$data[] = array('name' => $result->fullname,
     'position' => $result->position,
...

which would be cleaner.

Sign up to request clarification or add additional context in comments.

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.