在foreach循环中计算变量

时间:2013-05-12 20:39:14

标签: php if-statement foreach laravel laravel-4

我的Laravel 4控制器中有这个方法:

public static function getDelegateData($id, $status)
{
    $event = Event::find($id);

    foreach ($event->delegates as $delegate) {
        $delegate->status = DelegateStatus::find($delegate->pivot->delegate_status_id)->status;

        if($delegate->status == $status) {
            $total[] = $delegate->id;
        }
    }

    $data = "There are currently a total of $status delegates booked on to this event.";

    $data .= '<ul>';
        foreach ($event->delegates as $delegate) {
            $delegate->status = DelegateStatus::find($delegate->pivot->delegate_status_id)->status;

            if($delegate->status == $status) {
                $data .= '<li>';
                    $data .= $delegate->contact->first_name . ' ' . $delegate->contact->last_name;
                $data .= '</li>';
            }
        }
    $data .= '</ul>';

    return $data;
}

我无法计算(使用count())$ total数组中的项目。我怎样才能做到这一点?感谢。

1 个答案:

答案 0 :(得分:0)

好的伙计们,我用它来修理它:

public static function getDelegateData($id, $status)
{
    $event = Event::find($id);

    $total = array();

    foreach ($event->delegates as $delegate) {
        $delegate->status = DelegateStatus::find($delegate->pivot->delegate_status_id)->status;

        if ($delegate->status == $status) {
            $total[] = $delegate->status;
        }
    }

    $total = count($total);

    $data = "There are currently a total of $total $status delegates booked on to this event.";

    $data .= '<ul>';
        foreach ($event->delegates as $delegate) {
            $delegate->status = DelegateStatus::find($delegate->pivot->delegate_status_id)->status;

            if ($delegate->status == $status) {
                $data .= '<li>';
                    $data .= $delegate->contact->first_name . ' ' . $delegate->contact->last_name;
                $data .= '</li>';
            }
        }
    $data .= '</ul>';

    return $data;
}