1

I am having a database table named "updates" which contains fields "id" and "post" which are of type 'int' and 'text' respectively. Now I am retrieving all posts as follows:

$result = mysqli_query($con,"SELECT post FROM updates");
while($row=mysqli_fetch_row($result)){
$postsarray[] = $row;
}

Now I want to convert this array into JSON array as follows:

{
    "posts":[{
            "post1",
            "post2",
            ..
            }]
}

I have tried many ways but could not get that. Can anyone help me doing that?

4
  • 1
    json_encode($postsarray); Commented Mar 10, 2015 at 10:31
  • that is giving me :" [["post1"],["post2"]] ".. @caCtus Commented Mar 10, 2015 at 10:32
  • I am not sure the result you want (the one you show in your question) is Json. Commented Mar 10, 2015 at 10:38
  • 1
    Your JSON is not valid. { starts an object, not an array. Commented Mar 10, 2015 at 10:40

2 Answers 2

2
$result = mysqli_query($con,"SELECT post FROM updates");
while($row=mysqli_fetch_row($result)){
    $postsarray[] = $row[0];
}
$arr = array();
$arr['posts'] = $postsarray;
$json = json_encode($arr);

mysqli_fetch_row itself returns an array (the row), so you have to get the first element when adding into the $postsarray.

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

Comments

0

The PHP json_encode function translates the data passed to it to a JSON string which can then be output to a JavaScript variable. We demonstrate on this page with single level arrays. Other pages demonstrate using json_encode with multi-dimensional arrays and scalar values.

The PHP json_encode function returns a string containing the JSON equivalent of the value passed to it as we demonstrate here with a numerically indexed array:

<?php
$ar = array('apple', 'orange', 'banana', 'strawberry');
echo json_encode($ar); // ["apple","orange","banana","strawberry"]
?>

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.