user3693102
user3693102

Reputation: 11

Populate a 2d array partially from data in another multidimensional array

I am using fullcalendar (JSON) and want to use a foreach loop in a multidimensional array. What I've got is this:

echo json_encode(array(

    array(
        'id' => 111,
        'title' => $arr['new'][0] . ' new',
        'start' => $arr['booking_date'][0],
        'url' => "bookings/new/1",
        'color' => '#F7F8E0',
        'textColor' => 'black'
    ),

    array(
        'id' => 111,
        'title' => $arr['completed'][0] . ' completed',
        'start' => $arr['booking_date'][0],
        'url' => "bookings/completed/1",
        'color' => '#D8D8D8',
        'textColor' => 'black'
    ),

    array(
        'id' => 111,
        'title' => $arr['accepted'][0] . ' accepted',
        'start' => $arr['booking_date'][0],
        'url' => "bookings/accepted/1",
        'color' => '#E0ECF8',
        'textColor' => 'black'
    ),
));

Now I have to input every array manually, but how can I use foreach to do that for me?

I've tried something like this, but it didn't work. echo json_encode(array(

foreach($arr as $row) {
    array(
        'id' => 111,
        'title' => $arr['new'][0] . ' new',
        'start' => $arr['booking_date'][0],
        'url' => "bookings/new/1",
        'color' => '#F7F8E0',
        'textColor' => 'black'
    ),
}

Upvotes: 0

Views: 50

Answers (2)

mickmackusa
mickmackusa

Reputation: 48041

Use array_map() as a functional-style iterator. Demo

echo json_encode(
    array_map(
        fn($row) => [
            'id' => 111,
            'title' => $row['new'][0] . ' new',
            'start' => $row['booking_date'][0],
            'url' => 'bookings/new/1',
            'color' => '#F7F8E0',
            'textColor' => 'black'
        ],
        $array
    ),
    JSON_PRETTY_PRINT
);

Or array destructuring syntax in a foreach loop. Demo

$result = [];
foreach ($array as ['new' => [$t], 'booking_date' => [$b]]) {
    $result[] = [
        'id' => 111,
        'title' => $t . ' new',
        'start' => $b,
        'url' => 'bookings/new/1',
        'color' => '#F7F8E0',
        'textColor' => 'black'
    ];
}
echo json_encode($result, JSON_PRETTY_PRINT);

Upvotes: 0

Wezelkrozum
Wezelkrozum

Reputation: 1006

I guess you are looking for this:

<?php
$array = array();

$arr = array(
    array(
        'new' => array("Title 1"),
        'booking_date' => array("Booking date 1")
    ),
    array(
        'new' => array("Title 2"),
        'booking_date' => array("Booking date 2")
    )
);

foreach($arr as $row) {
    array_push($array, array(
        'id' => 111,
        'title' => $row['new'][0] . ' new',
        'start' => $row['booking_date'][0],
        'url' => "bookings/new/1",
        'color' => '#F7F8E0',
        'textColor' => 'black'
    ));
 }

echo json_encode($array);

Upvotes: 1

Related Questions