数组中的foreach不起作用,如何将值添加到数组?

时间:2014-06-06 00:48:11

标签: php arrays

我有这个复杂的数组。

    <?php

require_once('core/connect.php');
require_once('core/database.class.php');
require_once('core/controller.class.php');
require_once('core/settings.class.php');
$database   = new Database($db);
$controller = new Controller($db);
$settings   = new Settings($db);

$database->selectAll('SELECT * FROM bookings_calendar');
$result = $database->fetchAll();


$count = 0;
$arr = array();
foreach($result as $row)
{
    $arr['booking_date'][$count] = $row['booking_date']; 
    $arr['new'][$count]          = $row['new']; 
    $arr['completed'][$count]    = $row['completed']; 
    $arr['accepted'][$count]     = $row['accepted']; 
    $arr['cancelled'][$count]    = $row['cancelled']; 
    $count++;
}


    header("content-type: application/json"); 
    $year = date('Y');
    $month = date('m');

    echo json_encode(array(

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

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

        array(
            'id' => 111,
            'title' => $arr['new'][2] . ' new',
            'start' => $arr['booking_date'][2],
            'url' => "bookings/ordered-by-date/" . str_replace('-','', $arr['booking_date'][2]),
            'color' => '#F7F8E0',
            'textColor' => 'black'
        ),

    ));



?>

正如你所看到的,我只能通过改变索引来手动放置值,但是我想自动将所有元素放入该数组中,但不幸的是我不能在数组中使用foreach循环。而我的PHP技能并不是那么好,所以我正在寻找一些帮助。

任何帮助真的很感激。谢谢!

1 个答案:

答案 0 :(得分:0)

摆脱foreach并使用for循环。

$arr = array();
for($i=0; $i < count($result); $i++) {
    $arr[$i]['title'] = $result[$i]['new'] . ' new';
    $arr[$i]['whatever'] = $result[$i]['whatever'];
}

return json_encode($arr);