检查数组中是否有值

时间:2012-11-24 03:15:28

标签: php arrays isset

我正在尝试检查数组中是否有$subCat值,然后不添加它。我应该以每个$subCat中的一个结束,但是当我转储$details时,我仍然得到完整的数组。这是为什么?

foreach ($detailsFunction as $main) 
{
        $mainlisting = $main['listingId'];
        $mainCat     = strtolower($main['mainCat']);
        $subCatO     = strtolower($main['subCat']);
        $subCat      = str_replace(" ", "-", $subCatO);

        if(isset($subCat) && $subCat == $subCat)
        {

          $details[] = array('url'     => base_url().'listings/'.$mainCat.'/'.$subCat,
                         'mainCat' => $main['mainCat'],
                         'subCat'  => $main['subCat']   
                        );
        }
}

1 个答案:

答案 0 :(得分:1)

您是否关注保持$details数字的键?如果不是您可以添加$subCat作为其键的每个项目,并在添加之前检查该键是否存在:

foreach ($detailsFunction as $main) 
{
        $mainlisting = $main['listingId'];
        $mainCat     = strtolower($main['mainCat']);
        $subCatO     = strtolower($main['subCat']);
        $subCat      = str_replace(" ", "-", $subCatO);

        if(!array_key_exists($subCat, $details))
        {

          $details[$subCat] = array('url'     => base_url().'listings/'.$mainCat.'/'.$subCat,
                         'mainCat' => $main['mainCat'],
                         'subCat'  => $main['subCat']   
                        );
        }
}