0

How

$arr = array ();
while ($obj = mysql_fetch_object($result)) 
       $arr[] = $obj;

// add new key/value in same index
$arr['key'] = 'value';

echo json_encode ($arr);

In this construction not be result like I need

{
    0 =     {
        author = 3;
        id = 3;
        reader = 3;
        review = 4;
    };
    key = "value";
}

I need:

{
    author = 3;
    id = 3;
    reader = 3;
    review = 4;
    key = "value";
}
1
  • 1
    You can only get the desired output if there is only 1 row. Commented Jun 26, 2014 at 19:06

2 Answers 2

1

It looks like your query is only returning 1 row, so you don't need the while loop.

First things first though, please don't use mysql_*. Look into MySQLi or PDO

This is what you want instead:

$db = new mysqli(/* host, user, pass, db */);
$result = $db->query("SELECT * FROM aTable LIMIT 1");

$arr = $result->fetch_assoc();
$arr['key'] = 'value';

Edit: Ima go ahead and force you to use mysqli...

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

Comments

1

Move the value-assigning code into the loop, if you need to add some key-value pair to each and every item of the resulting array:

$arr = array ();
while ($obj = mysql_fetch_object($result))
  $obj->key = 'value';
  $arr[] = $obj;
}

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.