如果只有一个数组为空,而两个都为空则如何调用if条件,然后调用else条件?

时间:2018-11-16 06:11:36

标签: php codeigniter-3

我正在使用CodeIgniter。我从模型得到响应并显示在控制器上。

模型

//some code here
return array('secondary_data'=> $result,'primary_data' =>$result2);// sending to controller
// some code here

控制器

$result=$this->Search_model->get_search_name($cust_name);//calling model    
$data['secondary_data'] = $result['secondary_data'];
$data['primary_data'] = $result['primary_data'];

print_r($data['secondary_data']);
print_r($data['primary_data']);

输出

Array
(
    [0] => stdClass Object
        (
            [member_id] => 
            [customer_id] => 
            [first_name] => qwer
            [last_name] => poiu
            [email] => 
            [member_type] => 2

        )

)
Array
(
    [0] => stdClass Object
        (
            [member_id] => 1
            [customer_id] => 0011
            [first_name] => asdasd 
            [last_name] => asdasda
            [email] => bappyang68@gmail.com
            [member_type] => 1

        )

)

但是有时由于没有数据,我会得到print_r($data['primary_data'])的空数组。是的,有可能。;

但在下面的条件中,我正在检查数据计数count($data) > 0,如果发现为空,则调用else部分。

如果只需要一个数组,我不想调用其他部分。如果两个数组都为空,则应调用else部分

    if (count($data) > 0)
     {
        $data['title'] = "Search";
        $data['heading'] = "Search";
        $data['content'] = $this->load->view('search',$data,true);
        $this->load->view('dashboard/dashboard',$data);
        }
       else{
       echo "NO data available";
      }

任何想法该怎么做?谢谢

4 个答案:

答案 0 :(得分:2)

分别检查两个阵列的状态或条件

if (count($data['primary_data']) > 0 || count($data['secondary_data']) > 0)
{
   $data['title'] = "Search";
   $data['heading'] = "Search";
   $data['content'] = $this->load->view('search',$data,true);
   $this->load->view('dashboard/dashboard',$data);
}else{
   echo "NO data available";
}

答案 1 :(得分:1)

使用OR运算符尝试这种情况

if(!empty($data['primary_data']) || !empty($data['secondary_data'])){
//One or both array have values
}else{
//Both have no values
}

答案 2 :(得分:0)

您可以对两个数组使用单独的条件,如果其中一个不为空,则应用If条件,否则。

if ( !empty($data['secondary_data']) || !empty($data['primary_data']) ) {
    $data['title'] = "Search";
    $data['heading'] = "Search";
    $data['content'] = $this->load->view('search',$data,true);
    $this->load->view('dashboard/dashboard',$data);
} else {
   echo "NO data available";
}

答案 3 :(得分:0)

从$ data开始检查,然后从子数组开始检查

if(count($data) && (isset($data['secondary_data']) && !empty($data['secondary_data'])) || (isset($data['primary_data']) && !empty($data['primary_data']))){
      ....
    }else{
      ...
    }