PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, December 4, 2022

[FIXED] How to build a multidimensional json array with PHP while statement?

 December 04, 2022     jsonencoder, php     No comments   

Issue

As you can see in the code below, there are two appointments on the 2020-01-13 but they get generated as a separate array. How can I put them both on the same array since they are on the same day? I'm fetching all the information from a database using mysqli but for the sake of this code I'm only printing the necessary. It works but I need to know how to gather the appointments that have the same date in the same array.

php

//declare variable
$result = array();

//iterate
while($schedule = $result_data->fetch_assoc()){

//start time conversion into american time
// 24-hour time to 12-hour time 
$start_time  =date("g:i a", strtotime($schedule['start_time']));

//end time conversion into american time
$end_time  =date("g:i a", strtotime($schedule['end_time']));

$my_schedule_start .= $start_time;
$my_schedule_end .= $end_time;

$schedule_date= $schedule['cleaning_date'];


$result[] = array(
"$schedule_date" => [
    "number"=>'1',
    "badgeClass"=>'',
    "url"=>'url',

    "dayEvents"=>[
    "title"=>$schedule['first_name'].' '.$schedule['last_name'],
    "status"=>$schedule['cleaning_status'],
    "time"=>$start_time .' - '.$end_time
    ]
]
);  

}

//send response back to jquery
header('Content-Type: application/json');
echo json_encode($result);

this php prints this

[{"2020-01-15":{
    "number":"1",
    "badgeClass":"",
    "url":"url",
    "dayEvents":{
        "title":"Jen Doe",
        "status":"Booked",
        "time":"11:00 am - 12:00 pm"}
        }
        },
        {"2020-01-13":{
            "number":"1",
            "badgeClass":"",
            "url":"url",
            "dayEvents":{
                "title":"John Doe",
                "status":"Booked",
                "time":"2:00 pm - 5:00 pm"}
                }
                },
                {"2020-01-13":{
                    "number":"1",
                    "badgeClass":"",
                    "url":"url",
                    "dayEvents":{
                        "title":"Alfred Doe",
                        "status":"Booked",
                        "time":"11:00 am - 12:00 pm"}
                        }
                        }
                     ]

but my desired outcome is this

[{
        "2020-01-15": {
            "number": "1",
            "badgeClass": "",
            "url": "url",
            "dayEvents": {
                "title": "Jen Doe",
                "status": "Booked",
                "time": "11:00 am - 12:00 pm"
            }
        }
    },
    {
        "2020-01-13": {
            "number": "2",
            "badgeClass": "",
            "url": "url",
            "dayEvents": [{
                    "title": "John Doe",
                    "status": "Booked",
                    "time": "2:00 pm - 5:00 pm"
                },
                {
                    "title": "Alfred Doe",
                    "status": "Booked",
                    "time": "11:00 am - 12:00 pm"
                }
            ]
        }
    }
]

Solution

This code when creating the schedule, creates each days events indexed by the date itself, then when a new event is found it will check if this date is already set. If so, it will increment the count and add the new event. The only complication is that it needs to check if it only has 1 existing entry - this needs to be converted to an array first. To remove the index, the json_encode() uses array_values() first...

while($schedule = $result_data->fetch_assoc()){
    //start time conversion into american time
    // 24-hour time to 12-hour time
    $start_time  =date("g:i a", strtotime($schedule['start_time']));

    //end time conversion into american time
    $end_time  =date("g:i a", strtotime($schedule['end_time']));

    $my_schedule_start .= $start_time;
    $my_schedule_end .= $end_time;

    $schedule_date= $schedule['cleaning_date'];

    if ( isset($result[$schedule_date])){
        // Increment count
        $result[$schedule_date][$schedule_date]["number"]++;
        // Convert single item to array
        if ( !isset($result[$schedule_date][$schedule_date]["dayEvents"][0]))    {
            $result[$schedule_date][$schedule_date]["dayEvents"] = 
                [$result[$schedule_date][$schedule_date]["dayEvents"]];
        }
        // Add in new event to dayEvents
        $result[$schedule_date][$schedule_date]["dayEvents"][] = [
            "title"=>$schedule['first_name'].' '.$schedule['last_name'],
            "status"=>$schedule['cleaning_status'],
            "time"=>$start_time .' - '.$end_time
        ];

    }
    else    {
        // Create new days schedule
        $result[$schedule_date] = [
            "$schedule_date" => [
                "number"=>'1',
                "badgeClass"=>'',
                "url"=>'url',

                "dayEvents"=>[
                    "title"=>$schedule['first_name'].' '.$schedule['last_name'],
                    "status"=>$schedule['cleaning_status'],
                    "time"=>$start_time .' - '.$end_time
                ]
            ]
        ];
    }

}

header('Content-Type: application/json');
echo json_encode(array_values($result), JSON_PRETTY_PRINT);


Answered By - Nigel Ren
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing