1

I have a dynamic number of pages in my web project. It depends on data from the database. I may have 1 page or 10 pages. I put the data selected on each page in session, and finally want to build an array. At the moment I am building JSON from 4 arrays. (In session all the keys are level + int in ascending order. If session x is missing I don't have any data on 6+ levels)

$level1 = array();
$level2 = array();
$level3 = array();
$level4 = array();

if (isset($_SESSION['level1'])) {
    $level1 = $_SESSION['level1'];
}
//the same for 3 more levels in session


$array = array(
    "first"  => ($level1),
    "second" => ($level2),
    "third"  => ($level3),
    "fourth" => ($level4)
);

json_encode($array);

Example of output of the json_encode($array):

{"first":["1","2"],"second":["4","6","8","9"],"third":["13","14","17","18"],"fourth":["33","34","35","36"]}

I tried to check how would json_encode work with array_push(), but I get an array of JSON objects instead of a single json object.

$result = array();
array_push($result, ["key1" => $_SESSION["level1"]]);
array_push($result, ["key2" => $_SESSION["level2"]]);
array_push($result, ["key3" => $_SESSION["level3"]]);

echo json_encode($result);

and the output:

[{"key1":["1","2"]},{"key2":["4","5","6"]},{"key3":["13","14","15"]}]

I will make everything iteratively, but I want to know if it is possible to make a single JSON object instead of array of JSONs. Thanks!

1 Answer 1

2

You can just add the keys to the array without any need for a function.

$result = array();
$result["key1"] = $_SESSION["level1"];
$result["key2"] = $_SESSION["level2"];
$result["key3"] = $_SESSION["level3"];

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

1 Comment

Thank you! This solved my question! In some minutes I will be able to accept your answer

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.