数组中的Foreach循环

时间:2014-05-30 23:23:20

标签: php arrays

我正在使用fullcalendar(JSON)并希望在多维数组中使用foreach循环。我得到的是:

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'
    ),
));

现在我必须手动输入每个数组,但是如何使用foreach为我做这个呢?

我尝试过类似的东西,但它没有用。 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'
    ),
     }

1 个答案:

答案 0 :(得分:1)

我猜你正在寻找这个:

<?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);