1

I have mysql table with fields:

id | building | title | parent

And I want to create timeline calendar through fullcalendar.io.

I need to create this:

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

I did this:

$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']
    );
}

How can I add to this array element "children" in which all element will be collacted with same 'parent'? Thank you!

1 Answer 1

1

You could use the id as key of the array, and use it to store children values inside the parent element:

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']
        );
    }
}

// reset indices :
$data = array_values($data);

// create the JSON:
echo json_encode($data);
Sign up to request clarification or add additional context in comments.

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.