dtbam62840 2014-02-12 09:21
浏览 17
已采纳

in_array($ variable ['key'],$ another ['key'])无效

I can't get in_array to work. Its running inside a function which is defined in a file I have included, and then call the function from the original file... This is getting too complex, I will add the code:

index.php

$results = $database->get_results($query);
foreach ($results as $question) {
    echo '<div class="'.addQuestionClass($question).'"></div>';
}

functions.php

$sectionConfig = array(
    'amount' => '20',
    'types' => array('textarea', 'text', 'select', 'number'),
);

function addQuestionClass($question) {
    if(is_array($question)) {
        $order = 'order-'.$question['order'];
        $id = ' question-'.$question['id'];

        if(in_array($question['answer'], $sectionConfig['types'])) {
            $answertype = ' type-'.$question['answer'];
            echo 'true';
        } else {
            $answertype = null;
            echo 'false';
        }

        return $answertype;
    } else {
        return;
    }
}

The problem code is in my addClass function:

in_array($question['answer'], $sectionConfig['types'])

If I run the same code, with the array from $sectionConfig pasted in, like below, it works fine, but it never recognises in the format I have it above.

this works:

in_array($question['answer'], array('textarea', 'text', 'select', 'number'))

  • 写回答

2条回答 默认 最新

  • dongwubao4785 2014-02-12 09:26
    关注

    You are accessing $sectionConfig inside your function. By default, this is another scope and the code in your function doesn't know that $sectionConfig exists.

    You can try something like this:

    $sectionConfig = array(
        'amount' => '20',
        'types' => array('textarea', 'text', 'select', 'number'),
    );
    
    $results = $database->get_results($query);
    foreach ($results as $question) {
        echo '<div class="'.addQuestionClass($question,$sectionConfig).'"></div>';
    }
    
    function addQuestionClass($question,$sectionConfig) {
        if(is_array($question)) {
            $order = 'order-'.$question['order'];
            $id = ' question-'.$question['id'];
    
            if(in_array($question['answer'], $sectionConfig['types'])) {
                $answertype = ' type-'.$question['answer'];
                echo 'true';
            } else {
                $answertype = null;
                echo 'false';
            }
    
            return $answertype;
        } else {
            return;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大