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!