json_encode in particular way

时间:2017-06-15 10:15:08

标签: php json

so this my php

<?php
    include 'connect.php';
        $sql = "SELECT name from startup_schema";
    $result = mysqli_query($mysqli, $sql) or die("Error in Selecting " . mysqli_error($mysqli));
    $emparray =  array();
        while ($row = mysqli_fetch_assoc($result)) {
            $emparray[] = $row;
        }
    echo json_encode($emparray);
?>

which gives me a JSON like this

[{"name":"Flipkart"},{"name":"jagdish"},{"name":"mm"},{"name":"mouse"},{"name":"sa"},{"name":"sdasd"},{"name":"test"}]

now what I want is to edit my php code so that I fet a json like this

{suggestion: [{"name":"Flipkart"},{"name":"jagdish"},{"name":"mm"},{"name":"mouse"},{"name":"sa"},{"name":"sdasd"},{"name":"test"}]}

also notice that there is a square bracket at the starting right now but I want a curly bracket.

2 个答案:

答案 0 :(得分:3)

add your data in an array to get the desired result as

<?php
    include 'connect.php';
    $sql = "SELECT name from startup_schema";
    $result = mysqli_query($mysqli, $sql) or die("Error in Selecting " . mysqli_error($mysqli));
    $emparray =  array();
    while ($row = mysqli_fetch_assoc($result)) {
        $emparray[] = $row;
    }
    $arr=array('suggestion'=>$emparray);
    echo json_encode($arr);
?>

答案 1 :(得分:3)

if you change

while ($row = mysqli_fetch_assoc($result)) {
    $emparray[] = $row;
}

with

while ($row = mysqli_fetch_assoc($result)) {
     $emparray['suggestion'][] = $row;
}

you will get your output.