0

I am trying to create an array of custom json objects while traversing an array of results from a db query. However I m unable to get the correct response from the code.

I have tried creating arrays and traversing it. Below is my code to show what all I have tried. P.S. I am newbie to php so, I am sorry if its a rookie mistake or anything.

$response = array();
    while($row = $result->fetch_assoc()){
        $flag = false;
        $sample_obj = json_encode(json_decode("{}"));
        $index = 0;
        $length = count($response);
        for($x = 0; $x < $length; $x++){
            if($response[$x]->session_id == $row->session_id){
                $sample_obj = $row;
                $flag = true;
                $index = $x;
                break;
            }
        }
        if($flag == true){
            $sample_array = array();
            $sample_array[] = $row;
            $response[$index]->sessions[] = $row;
        } else {
            $sample_array = array();
            $sample_array[] = $row;
            $sample_obj["session_id"] = $row->session_id;
            $sample_obj["sessions"] = array();
            $sample_obj["sessions"] = $sample_array;
            $response[] = $sample_obj;
        }
        // $response[] = $row;
    }
    $res["statusCode"] = 201;
    $res["success"] = true;
    $res["records_found"] = true;
    $res["results"] = $response;
    header('Content-Type: application/json;charset:utf-8');
    echo json_encode($res,JSON_PRETTY_PRINT);

I want output like

{
    "statusCode": 201,
    "success": true,
    "records_found": true,
    "results": [
        {
            "session_id" : 1,
             "sessions"  : [
              {
                   "session_id" : 1,
                   "creation_time" : "some_timestamp",
                    "active_session" : true
              },

              {
                   "session_id" : 1,
                   "creation_time" : "some_timestamp",
                    "active_session" : false
              },

              {
                   "session_id" : 1,
                   "creation_time" : "some_timestamp",
                    "active_session" : false
              }
              ]
        }
    ]
}

But I m getting very wrong output like :

{
    "statusCode": 201,
    "success": true,
    "records_found": true,
    "results": [
        "A}"
    ]
}

I dont know why this "A}" is being shown instead of my session array.

2 Answers 2

1

The following line causes errors.

    $sample_obj = json_encode(json_decode("{}"));

Replacing it with:

 $sample_obj = [];

would fix the problem.

Checkout the following working example:

<?php
$response = array();
while($row = $result->fetch_assoc()){
    $flag = false;
    $sample_obj = [];
    $index = 0;
    $length = count($response);
    for($x = 0; $x < $length; $x++){
        if($response[$x]->session_id == $row->session_id){
            $sample_obj = $row;
            $flag = true;
            $index = $x;
            break;
        }
    }
    if($flag == true){
        $sample_array = array();
        $sample_array[] = $row;
        $response[$index]->sessions[] = $row;
    } else {
        $sample_array = array();
        $sample_array[] = $row;
        $sample_obj["session_id"] = $row->session_id;
        $sample_obj["sessions"] = array();
        $sample_obj["sessions"] = $sample_array;
        $response[] = $sample_obj;
    }
    // $response[] = $row;
}
$res["statusCode"] = 201;
$res["success"] = true;
$res["records_found"] = true;
$res["results"] = $response;
header('Content-Type: application/json;charset:utf-8');
echo json_encode($res,JSON_PRETTY_PRINT);

or with sample data:

$rows = [(object)['session_id' => 1]];
$response = [(object)['session_id' => 2]];
foreach($rows as $row){
    $flag = false;
    $sample_obj = [];
    $index = 0;
    $length = count($response);
    for($x = 0; $x < $length; $x++){
        if($response[$x]->session_id == $row->session_id){
            $sample_obj = $row;
            $flag = true;
            $index = $x;
            break;
        }
    }
    if($flag == true){
        $sample_array = array();
        $sample_array[] = $row;
        $response[$index]->sessions[] = $row;
    } else {
        $sample_array = array();
        $sample_array[] = $row;
        $sample_obj["session_id"] = $row->session_id;
        $sample_obj["sessions"] = array();
        $sample_obj["sessions"] = $sample_array;
        $response[] = $sample_obj;
    }
    // $response[] = $row;
}
$res["statusCode"] = 201;
$res["success"] = true;
$res["records_found"] = true;
$res["results"] = $response;
header('Content-Type: application/json;charset:utf-8');
echo json_encode($res,JSON_PRETTY_PRINT);
Sign up to request clarification or add additional context in comments.

Comments

0

you can prewrite what ever you want in a php array like this:

$arr = array(
    "val_1" => "value1",
    "val_2" => "value2",
    "val_3" => array(
        "moreVals" => "another value",
        "smtng" => "smtng"
    )
);

and than convert it to json like so:

$json = json_encode($arr, JSON_PRETTY_PRINT | JSON_FORCE_OBJECT);

I use this method all the time and it works fine for me.

I hope, it hepls.

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.