如果数组为空,则加载消息

时间:2012-12-27 23:18:25

标签: php arrays string

我有以下代码,但我不确定为什么我的数组仍然是空的,因为我的想法是如果foreach为空它应该加载带有'No Open Homes'的else语句:

$openHomeTimes = array();

                    if(!empty($detail) && in_array('OpenHomes', $detail))
                    {
                        foreach ($detail['OpenHomes'] as $openHome) 
                        {   
                            $startO        = $openHome['Start'];
                            $finishO       = $openHome['End'];
                            $startConvert  = preg_replace('~\D~', '', $startO);
                            $start         = date('D j M g a',$startConvert / 1000);
                            $finishConvert = preg_replace('~\D~', '', $finishO);
                            $finish        = date('g:ia',$finishConvert / 1000);

                            $openHomeDetail = $start." - ". $finish;

                            $openHomeTimes[] = $openHomeDetail;


                        }
                    }else{
                        if(!empty($openHomeTimes))
                        {
                            $message = 'No Open Homes';

                            $openHomeTimes = $message;


                        }
                    }

1 个答案:

答案 0 :(得分:0)

如果我没有完全误解你,简单的逻辑修复可能就足够了。 foreach不是外部if / else构造的条件。

                $openHomeTimes = array();

                if(!empty($detail) && in_array('OpenHomes', $detail))
                {
                    foreach ($detail['OpenHomes'] as $openHome) 
                    {   
                        $startO        = $openHome['Start'];
                        $finishO       = $openHome['End'];
                        $startConvert  = preg_replace('~\D~', '', $startO);
                        $start         = date('D j M g a',$startConvert / 1000);
                        $finishConvert = preg_replace('~\D~', '', $finishO);
                        $finish        = date('g:ia',$finishConvert / 1000);

                        $openHomeDetail = $start." - ". $finish;

                        $openHomeTimes[] = $openHomeDetail;


                    }
                }

                //Always check for emptiness
                if(empty($openHomeTimes))
                {
                    $message = 'No Open Homes';

                    $openHomeTimes = $message;
                }