繁体   English   中英

如何在PHP中将关联数组与result_array进行比较

[英]How to compare associative array with result_array in PHP

需要基于“内容”表有条件地绑定页面下拉列表。 页面标题存储在关联数组中,“内容”表中存储有页面代码。 这是代码

返回页面标题的功能

    public function getPageTitles(){    
     $pageTitles = array("Home"=> "Home", 
              "AboutUs"=> "About Us", //AboutUs will save in database as pageCode
              "Features"=> "Features",
              "ContactUs"=> "Contact Us");

     return $pageTitles;
  }

检查页面是否有内容的功能:

public function getPageTitlesWithNoContent()
{
    $pageTitles = $this->getPageTitles();

    $this->db->distinct('pageCode');
        $this->db->select('pageCode');
        $this->db->from('content');
    $this->db->where('status', 1);      
    $data = $this->db->get();

    $queryResult = $data ? $data->result_array() : 0 ;

    $emptyPageTitle = array();

    foreach($pageTitles as $x => $x_value)
    {
        $hasContent = in_array($x, $queryResult);

        if (!$hasContent){ 
         $emptyPageTitle[$x] = $x_value;
        }
    }

    return $emptyPageTitle;
}

此函数返回所有页面标题。

检查表中的名称字段是否相同? 用大写的第一个字符?

还要在此循环中更改代码:

foreach($pageTitles as $x => $x_value)
{
    if (in_array($x, $queryResult)){ 
     $emptyPageTitle[$x] = $x_value;
    }
}

我删除! 检查条件为负

按照@TamilvananN的指导,我打印了queryResult并尝试了以下解决方法:

    foreach($pageTitles as $x => $x_value)
        {
            foreach ($queryResult as $item) 
            {
                if (!($x == $item['pageCode'])){ 
                 $emptyPageTitle[$x] = $x_value;
                }
            }
        }

它正在工作,但是如您所见,这是一个循环的循环..这可能会非常昂贵..请您分享一种比较结果的快速方法。

@NMathur我想你几乎明白了。 在该代码中为您做了一些更改,请检查一下。

public function getPageTitlesWithNoContent() {

    $pageTitles = $this->getPageTitles();

    $this->db->select('pageCode');
    $this->db->from('content');
    $this->db->where('status', 1); 
    $this->db->group_by('pageCode');      
    $query = $this->db->get();

    $queryResult = array();

    foreach ($query->result_array() as $row) { // This loop should need to form an array based on query result
       $queryResult[$row['pageCode']] = $row['pageCode'];
    }

    $emptyPageTitle = array_diff_key($pageTitles,$queryResult); // Compares the keys from array1 against the keys from array2 and returns the difference

    return $emptyPageTitle;

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM