1

I have a webservice which gives data as json form mysql database.

PHP webservice

<?php
    $conn = mysql_connect('localhost','root','');
    mysql_select_db('db', $conn);
    $query = mysql_query("SELECT id,group FROM faq");
    //$query content is:
    // Array ([id]=>faq1 [group]=>hardware) Array ([id]=>faq2 [group]=>software) 

    $faq = array();
    while($row = mysql_fetch_assoc($query)) {
        $faq[] = $row // <= ????????
    }

    header('Content-type: application/json');
    return json_encode($faq);
?>

JSON output that I get

[
    {
        "id": "faq1",
        "group": "hardware"
    },
    {
       "id": "faq2",
       "group": "software"
    }
]

JSON output that I want to have

[
    {
        "id": "faq1",
        "group": {
            "id": "hardware"
        }
   },
   {
       "id": "faq2",
       "group": {
            "id": "software"
       }
   }
]

I want to get this JSON data as result but I really couldn't have success on this. So how should I need to edit my "PHP webservice" to get this json result?

4
  • 2
    Not an answer but mysql_ is deprecated, use mysqli_ instead Commented May 17, 2013 at 14:15
  • What does your current code output? Commented May 17, 2013 at 14:15
  • @Henrique Barcelos I tried to summarize my code and for this I didn't mention my current json result. So, I'm not happy with my current result format:) Commented May 17, 2013 at 14:34
  • @Pete O'Connell I tried to summarize my code and for this I didn't mention my current json result. I've added it to my question now. Commented May 17, 2013 at 14:37

4 Answers 4

5
$faq = array();
while($row = mysql_fetch_assoc($query)) {
   $faq[] = array(
      'id' => $row['id'],
      'group' => array(
         'id' => $row['group']
       )
   );
}
Sign up to request clarification or add additional context in comments.

Comments

2

Do this first:

$row['group'] = Array('id' => $row['group']);

Comments

1

Construct array like this

$arr = array();
$id = 0;
while($row = mysql_fetch_assoc($query)) {
    $arr[$i]['id'] = $row['id'];
    $arr[$i]['group']['id'] = $row['group'];
    $i++;
}

$json = json_encode($arr);

1 Comment

if you change $id = 0; as $i = 0; this works also. But @Michael Marr 's way looks like easier to me. Ofcourse thank you!
0

try this :

$arrayJson["id"] = $row["id"];
$arrayJson["group"]["id"] = $row["group"];
echo json_encode($arrayJson)

2 Comments

Without using a $i counter as @chandresh_cool did, this gives only one object(the last one) after the while loop. Thanks anyway.
yeah , i forgot you have multiple rows :(

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.