1

I am formating an array data into Json_encode using php. This array data is from my database. I have described how I am doing it here

$pens=$db->fetchAllPens();  //This fetches the list of pens
$a = array();
$response = array();

$response["success"]="true";

while ($pen = mysqli_fetch_array($pens)) {    
    $response["label"]["id"]=$pen["ID"];
    $response["label"]["name"] = $pen["name"];

    array_push($a,$response);
}

    echo json_encode($a,JSON_PRETTY_PRINT);

The above code gives me the below output

[
{
    "success": "true",
    "label": {
        "id": "1",
        "name": "nimble"
    }
},
{
    "success": "true",
    "label": {
        "id": "2",
        "name": "lopsel"
    }
}
]

However I am expecting an output below

{
"success":true,
"label":[
    {
        "id":1,
        "name":"nimble"

    },
    {
        "id":2,
        "name":"lopsel"

    }
]
}

Please is there a way to achieve the desired results.

3 Answers 3

2
$pens = $db->fetchAllPens();  //This fetches the list of pens
$response = array('success' => true, 'label' => array());

while ($pen = mysqli_fetch_array($pens)) {    
    $response['label'][] = array('id'   => $pen['ID'],
                                 'name' => $pen['name']
                                );
}

echo json_encode($response,JSON_PRETTY_PRINT);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for helping
1

You are writing to the wrong variable in each loop cycle.

Instead do the following:

while ($pen = mysqli_fetch_array($pens)) {
  $data[] = [
    'id' => $pen['ID'],
    'name' => $pen['Name'],
  ];
}

$response['label'] = $data;

echo json_encode($response,JSON_PRETTY_PRINT);

1 Comment

Thanks for helping
1

Start by putting the status directly into the $a array.

Then place the rows data into $a['label'][] i.e. a new occurance of the $a['label'] array

$pens=$db->fetchAllPens();  //This fetches the list of pens
$a = array();

$a["success"] = "true";

while ($pen = mysqli_fetch_array($pens)) {    
    $response = array();

    $response["id"]     = $pen["ID"];
    $response["name"]   = $pen["name"];

    $a['label'][]       = $response;
}
echo json_encode($a,JSON_PRETTY_PRINT);

Result:

{
    "success": "true",
    "label": [
        {
            "id": 1,
            "name": "fred"
        },
        {
            "id": 2,
            "name": "Bill"
        }
    ]
}

2 Comments

For the effort. All answers are equal but with a slight difference.
That is true, and I was suppose to accept only one as an answer, anyways kindly check this question out if you can be of help stackoverflow.com/q/42762250/2595059

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.