Manipulating multidimensional arrays in PHP and converting them to JSON format

I have a MySQL table with the following fields:

id | building | title | parent

Now, I am looking to implement a timeline calendar using fullcalendar.io.

This is the structure I aim to create:

{ id: '1', building: '460 Bryant', title: 'Auditorium D', children: [
   { id: '2', title: 'Room D1' },
    { id: '3', title: 'Room D2' }
 ] }, and so on...

To achieve this, I have written the following code snippet:

$query = "SELECT * FROM resources ORDER BY id";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();

foreach($result as $row)
{
    $data[] = array(
        'id'       => $row['id'],
        'building' => $row['building'],
        'title'    => $row['title']
    );
}

My question is, how can I modify this array to include an element called "children" that groups all elements with the same 'parent'? Any help would be greatly appreciated. Thank you!

Answer №1

To efficiently store children values inside the parent element, you can utilize the id as the key in an array:

foreach($result as $row)
{
    $id = $row['id'] ;
    $id_parent = $row['parent'] ;

    if ($id_parent)
    {
        $data[$id_parent]['children'][] = array(
            'id'       => $id,
            'title'    => $row['fname']
        );
    }
    else
    {
        $data[$id] = array(
            'id'       => $id,
            'building' => $row['building'],
            'title'    => $row['fname']
        );
    }
}

// reindex the array :
$data = array_values($data);

// generate JSON output:
echo json_encode($data);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to send a specific row to an AJAX function within a Codeigniter view

Having just started using codeigniter, I am looking to transfer a row returned from the controller via the model to an ajax function within a view. The current code snippet below demonstrates how I am able to retrieve data from the model in the controlle ...

Utilize PHP to transform JSON data into JavaScript

Hello, I am a newcomer to Stackoverflow and I need some assistance. My issue involves converting JSON with PHP to JavaScript. I am using PHP to fetch data from a database and create JSON, which I then want to convert for use in JavaScript as an object (obj ...

CodeIgniter throws an error message stating, "Undefined property $db"

When working with CodeIgniter 3.1.3, I decided to extend CI_Model in MY_Model.php located at application/core/: class MY_Model extends CI_Model { public function __construct($id = NULL) { parent::__construct(); $this->load($id); ...

jQuery AJAX POST Request Fails to SendIt seems that the

The issue I am experiencing seems to be directly related to the jQuery $.ajax({...}); function. In PHP, when I print the array, I receive a Notice: Undefined index. I would greatly appreciate any advice or guidance on this matter. <script> $(docume ...

unable to decode JSON into a structure

After receiving an attribute in JSON format from a REST service and capturing it with an invokeHTTP processor, I am looking to incorporate it into a JSON content flow using the JOLT processor. My existing content looks like this: { "id": 123, "use ...

stopping php exec from waiting

I have been trying for some time to make my PHP code run asynchronously. I've come across various posts discussing this topic. My goal is to execute additional formatting in my script but have it return quickly without waiting for the exec command re ...

Arranging elements within an outer array by the contents of their inner arrays

I need help organizing an array based on the alphabetical order of a specific value within the inner arrays. For example: I want to sort this array by the prefix "old," so old A, old B, etc. const array = [ { personName: "Vans", personTags: ["young", " ...

Unable to retrieve JEnumerable<JToken> child elements

When trying to call the code below in its current state, I am getting ,"Name":"Newtonsoft.Json.Linq.JEnumerable`1[Newtonsoft.Json.Linq.JToken]" as a result. If I modify the relevant line to var property = myObject[propertyNames.Last()].FirstOrDefault(); ...

Exploring locations using the Google Geolocation API

I have a website and am trying to determine the location of my visitors. I came across this code on Google Code: <script type="text/javascript" src="gears_init.js"></script> <script type="text/javascript"> var geo = google.gears.factory ...

Implementing Spam Prevention in the Php Contact Form

Can anyone provide assistance in resolving this issue? I am attempting to integrate this code into my contact form to prevent spam emails, but it is not functioning as expected. Html: Access code: <input type="text" name="code" /><br /> Kin ...

Having trouble interpreting JSON attribute "null"

I encountered a problem while attempting to parse a JSON "null" property. Can someone help me understand what the issue might be? The JSON I used was as follows: { "properties" : { "null" : { "value" : false } } } I validated th ...

I received incorrect JSON data

Take a look at my PHP code for encoding JSON data from MySQL database. Check out the URL . I validated the JSON data using JSONLint, which showed it as valid. However, instead of receiving the data in JSON format, I got the result [false]. Can anyone hel ...

Looking for a PHP program that utilizes the Shunting Yard algorithm to interpret and evaluate a mathematical expression in string format, ultimately producing a boolean result

I am in search of a solution that can interpret a string in php and execute basic math operations, providing a boolean result to determine if the expression is true or false. For instance: Sue inputs "3*{mysalary}/9=10000" PHP breaks this down into two ...

Using jQuery to interact with a web service - overcoming cross-domain restrictions

Attempting to connect to a WCF service using a jQuery client. Referencing this specific example: http://www.codeproject.com/KB/aspnet/WCF_JQUERY_ASMX.aspx#4 Everything functions properly when the client webpage is on the same domain as the service. Howe ...

ran out of memory after utilizing approximately 2MB of memory

I am facing a memory issue with my PHP script. Every time the script runs, it crashes and displays the following error message: PHP Fatal error: Allowed memory size of 2097152 bytes exhausted (tried to allocate 3027408 bytes) in test.php on line 9 To di ...

Can anyone recommend a speedy sorting algorithm for an extensive list of objects in JavaScript?

Struggling to organize a large array of 2000 elements in ReactJS using JavaScript. The array includes: data = [ { index: 0, id: "404449", product_name: "ette", brand_name: "Dyrberg/Kern", base_pri ...

Expanding the capabilities of the Google Fit API by implementing support for a variety of data

I have implemented the Google Fit API with multiple user scopes. How can I incorporate multiple data types for each data source? Is it possible to add this as a data source? { "dataStreamName":"MyDataSource", "type":&quo ...

Tips for dividing the elements of an array by 4 using Javascript or ReactJS

I have a large array of items that I need to organize into 4 sections in order to improve the display on my user interface. The array contains up to 20 objects, and my objective is to create 4 separate arrays each containing 5 objects. let attributes = [ ...

When submitting the form, does it trigger the opening of the PHP file?

Let's get straight to the point. Before anything else, I want to say THANKS IN ADVANCE. So, here's what's happening: When I submit the form I created, it goes through the submission process and all, but then it redirects the page to the PHP ...

Is there a Solution for Dealing with Floating Point Rounding Errors?

I've been working on a PHP system and encountered an issue with rounding. Upon investigating, I discovered that the problem lies within the round function in PHP. For example... Rounding 2047.615 to 2 decimal places results in 2047.62 (as expected) ...