如何检查特定值的索引是否存在

时间:2019-01-02 12:16:43

标签: php arrays indexing

我有一个像这样的php数组。

Array
(
    [first_year] => Array
        (
            [1] => Array
                (
                    [0] => Array
                        (
                            [distiction] =>  , 2, 3, 4, 5, 6,  , 8, 9
                            [name] => ‌Mark
                            [status] => Pass with credit
                        )

                )

            [2] => Array
                (
                    [0] => Array
                        (
                            [distiction] =>  , 2, 3, 4, 5, 6, 7,  , 9
                            [name] => ‌John
                            [status] => 
                        )

                )

        )
)

我通过print_r($dataArray[$academic_year][$major])得到了这些数据。 如何检查$ dataArray [$ academic_year] [$ major] [$ year]并检查[first_year]是否具有值?我已经尝试过empty()!array_filter()$dataArray[$academic_year][$major][$year] == []。  但是没有一个对我有用。谢谢。

3 个答案:

答案 0 :(得分:0)

您可以使用:

if (array_key_exists($year, $dataArray[$academic_year][$major])) {
    if ($dataArray[$academic_year][$major][$year]){
        //your code here
    }
}

答案 1 :(得分:0)

尝试这个:

如果$dataArray[$academic_year][$major][$year]返回数组,则

if ( isset( $dataArray[$academic_year][$major][$year] ) &&  count($dataArray[$academic_year][$major][$year])) {
    //your code here
}

答案 2 :(得分:0)

合并运算符怎么样?

仅在不存在默认行为时返回默认行为:

$data = $dataArray[$academic_year][$major][$year] 
        ?? ['distiction' => '', 'name' => '', 'status' => ''];

$data = $dataArray[$academic_year][$major][$year] ?? null;
if (is_array($data) && !empty($data)) {
  // Your code...
}