PHP - check if one or more array field exist
I have a array like this:
array('prefix1_field' => 34,
'prefix1_anotherfield' => 345,
'prefix1_andanotherfield' => 565,
'anotherprefix_field' => 34,
'anotherprefix_anotherfield' => 345,
'anotherprefix_andanotherfield' => 565,
'prefix3_anotherprefix_field' => 34, // <- 'anotherprefix' here should be ignored
'prefix3_anotherfield' => 345,
'prefix3_andanotherfield' => 565,
...
);
How can I make a function that check开发者_高级运维s if there are any fields in this array that start with prefix1_
for example?
function check_array_key_prefix_exists($array, $key_prefix) {
$keys = array_keys($array);
foreach ($keys as $key) {
if (0 == substr_compare($key, $key_prefix, 0, strlen($key_prefix))) {
return true;
}
}
return false;
}
Something like:
function check($arr,$prefix) {
foreach($arr as $key => $value) {
if(strcmp(substr($key,0,strlen($prefix)),$prefix)==0) {
return true;
}
}
return false;
}
Why not use regular expressions?
function array_has_key_prefix( $array, $key_prefix ) {
foreach($arr as $key => $value) {
if( preg_match( "/^" . $key_prefix . "/", $key ) )
return true;
}
return false;
}
I'd prefer to restructure the array as follows:
$data=array('prefix1'=>array(
'field'=>34,
'anotherfield'=>345,
),
'prefix2'=>array(
'field'=>56,
),
...etc.
With that structure, you can just make a quick call to the standard PHP function array_key_exists().
With the structure you have, you'd have to basically roll your own alternative to array_key_exists(), which would involve a foreach() loop and explode() to break the key into bits.
I won't give much as informatio and I'll expilicitly write s.t. similar to the post of Dominique Roger.
function check_array_key_prefix_exists($array, $key_prefix) {
$keys = array_keys($array);
foreach ($keys as $key) {
if (preg_match("#^$key_prefix", $array) {
return true;
}
}
return false;
}
I don't know if I've answerd your Question part because I didn't run it into he bwowser. Good Luck
精彩评论