Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用php在web应用程序中使用动态数组_Php_Jquery_Arrays_Codeigniter - Fatal编程技术网

使用php在web应用程序中使用动态数组

使用php在web应用程序中使用动态数组,php,jquery,arrays,codeigniter,Php,Jquery,Arrays,Codeigniter,我的网站依赖于用户输入提供的独特内容 所以他们输入“运动”,他们会收到基于运动的内容。这很简单。然而,一旦我开始添加更多的关键字,它就会变得有点复杂,至少在我这样做的方式上 我需要开始不断地检查用户输入的数据是否是数组,并处理不同的数据 我目前正在使用Codeigniter的会话类存储用户的选择,然后根据其值检索和操作数据 因此,他们提交表单并运行my JS: $('#topics_form').submit(function() { var topic = document.getEl

我的网站依赖于用户输入提供的独特内容

所以他们输入“运动”,他们会收到基于运动的内容。这很简单。然而,一旦我开始添加更多的关键字,它就会变得有点复杂,至少在我这样做的方式上

我需要开始不断地检查用户输入的数据是否是数组,并处理不同的数据

我目前正在使用Codeigniter的会话类存储用户的选择,然后根据其值检索和操作数据

因此,他们提交表单并运行my JS:

$('#topics_form').submit(function() {
    var topic = document.getElementById('topics_filter').value
    $.ajax({
        type: "POST",
        url: 'ajax/update_session_topic',
        dataType: 'json', 
        data: { topic: topic },
            success: function(){
                load_custom_topics()
            }
    });
    return false;
});
然后更新会话主题在我的AJAX模型中运行

public function update_session_topic()
{
    if ($this->session->userdata('active_topic') == FALSE) 
    {
        $array['active_topic'] = $this->input->post('topic');
        $this->session->set_userdata($array);
        return true;
    } else {
        $this->page_model->add_session_topic($this->input->post('topic'));
        return true;
    }
}
当只有1个值时,这没什么大不了的

然而,当尝试添加第二个值时…我不得不检查它是否是数组,或者使其成为数组

    public function add_session_topic($current_filter)
    {
        $session = $this->session->userdata('active_topic');
        if (is_array($session) == false)
        {
            $session = array($this->session->userdata('active_topic'));
        } 
        foreach ($session as $keyword)
        {
            if ($keyword == $current_filter)
            {
                return false;
            }
        }
        $session[] = $current_filter;
        $active['active_topic'] = $session;
        $this->session->set_userdata($active);
        return true;
    }
我的观点也是如此

这有点烦人,我希望有更好的方法来做到这一点。我对PHP/codeigniter还是新手,所以我对任何事情都持开放态度


谢谢

如果我是你,我会一直像数组一样工作。您可以像
(array)$session
那样进行简单的强制转换,如果它是一个数组,它将被单独保留,或者如果它不是数组,它将被转换为类似
的数组($session)
。只要它可以是字符串或数组,就没有理由进行检查。然后只有处理数组的逻辑。我正试图这样做,但我担心的是,当我从会话->用户数据中提取时,如果已经有一个数组,它会在上面创建另一个多维数组。有什么方法可以防止这种情况发生吗?它会将一个数组强制转换为一个什么都不做的数组。我不熟悉“强制转换”这个词。。。你介意详细说明一下吗?我做了一个快速搜索,但没有很好的解释出现。是指将某个内容强制为特定类型(字符串、对象、数组等)。将类型放在变量前面的括号中:
$arr=(array)$thevariable