ShaShads
ShaShads

Reputation: 572

Recursively search array for key match or value match in 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.

Upvotes: 0

Views: 1112

Answers (3)

bitWorking
bitWorking

Reputation: 12665

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));

Upvotes: 1

karmafunk
karmafunk

Reputation: 1453

// 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)) {
        return $this->isValid($category, $data[$var]);
    } elseif($val === $category) {
        return true;
    }
}
return false;
} 

Upvotes: 0

deceze
deceze

Reputation: 522175

} elseif (is_array($val)) {
    return $this->isValid($category, $val);
    ^^^^^^
}

You need to return even from a recursive call.

Upvotes: 3

Related Questions