在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.
我有一个可以深层次的数组,例如 p>
'待售'=> 阵列( 'Baby& Kids Stuff'=> array( 'Car Seats& Baby Carriers', ), ), 'For Rent'=> 数组( '其他'=>数组( '婴儿服装', ), '价格'=>'hhhhhh', ), code> pre> \ n我要做的是搜索数组键和值以匹配字符串,到目前为止我已经提出了这个但是它没有用... p>
//验证类别 公共函数isValid($ category,$ data = false){ if 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; } } } code > pre>
我不知道自己做错了什么,非常感谢。 p> div>
答
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));
答
} elseif (is_array($val)) {
return $this->isValid($category, $val);
^^^^^^
}
You need to return
even from a recursive call.
答
// 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;
}