doudang4857 2013-03-15 15:49
浏览 27
已采纳

在PHP中递归搜索数组以获得密钥匹配或值匹配?

I have an array that can be many levels deep for example

'For Sale' => array(
        'Baby & Kids Stuff' => array(
            'Car Seats & Baby Carriers',
                            ),
        ),
'For Rent' => array(
        'Other' => array(
            'Baby Clothes',
        ),
         'Prices' => 'hhhhhh',
                   ),

What I am trying to do is search both the array keys and values to match a string, I have come up with this so far but it isn't working...

// validate a category
public function isValid($category, $data = false) {

    if(!$data) {
        $data = $this->data;
    }
    foreach($data as $var => $val) {
        if($var === $category) {
            return true;
        } elseif(is_array($val)) {
            $this->isValid($category, $data[$var]);
        } elseif($val === $category) {
            return true;
        }
    }
}   

I don't know what I am doing wrong, many thanks.

  • 写回答

3条回答 默认 最新

  • dpg98445 2013-03-15 16:16
    关注

    if you're using PHP >= 5.1.0 than it's better to use RecursiveArrayIterator / RecursiveIteratorIterator

    $arr = array(
        'For Sale' => array(
            'Baby & Kids Stuff' => array(
                'Car Seats & Baby Carriers',
            ),
        ),
        'For Rent' => array(
            'Other' => array(
                'Baby Clothes',
            ),
            'Prices' => 'hhhhhh',
        ),
    );
    
    function isValid($category, array $data)
    {
        $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($data), RecursiveIteratorIterator::CHILD_FIRST);
    
        foreach ($iterator as $key => $value) {
            if (is_string($key) && ($category == $key)) {
                return true;
            }
            if (is_string($value) && ($category == $value)) {
                return true;
            }
        }
        return false;
    }
    
    var_dump(isValid('Baby Clothes', $arr));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?