0

I am trying to know if the new data can be added to JSON before encoding it?

I am retrieving the data from MySQL database in the following way:

//fetch the data from the database
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
    $to_encode[] = $row;
}

which gives me this:

[
    {
        name: "aaa"
    },
    {
        name: "bbb"
    }
]

Then I encode it to JSON with:

$array1 =  json_encode($to_encode)

I wanted to know if I can add more data into the array before encoding it to make it like this?

[
    {
        name: "aaa"
        age: '5'
    },
    {
        name: "bbb"
        age: '5'
    }
]

or should I decode the encoded JSON, add the new values and then encode it back?

1
  • If you're retrieving all of the information from the database, it's more efficient to use a join statement so that the name and age appear in one row and to iterate through those results. Commented Feb 2, 2016 at 4:37

3 Answers 3

1

Simply you can do like this:

//fetch the data from the database
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
    $to_encode[] = $row;
}

for ($i = 0; $i < count($to_encode); $i++) {
$to_encode[$i]['age'] = '14';
}

$array1 =  json_encode($to_encode);
print_r($array1);
Sign up to request clarification or add additional context in comments.

2 Comments

the key 'name' and its value is retrieved from the database. I just want to add another key value pair to the same object with key being age for example
@HardikVasa, I have updated my answer. I don't know how you will make age dynamic. but i used hard-coded 14. It might help you.
1

Try something like this :

$i=0;
 while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
    $to_encode[$i]["name"] = $row;
    $to_encode[$i]["age"] = 5;
    $i++;
}
$array1 =  json_encode($to_encode)

2 Comments

this does not work...it adds all the 'name' keys and its values and then adds one 'age' key value at the end
no disrespect but your accepted answer will take 2 loop which is time consuming. Thanks.
0

You can push an array to the $row variable, the idea is to build the array before you use json_encode

$to_encode = [];

while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
    $age = array('age'=>5);
    array_push($to_encode,$row);
    array_push($to_encode,$age);
}

$array = json_encode($to_encode);

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.