我有以下数组。我想得到的值是'1',键应该是'wf_status_step%'。如何为此编写PHP脚本?
[ini_desc] => 31.07 Initiative1
[mea_id] => 1
[status] => 4
[name] => 31.07 Measure1
[scope] => NPR
[sector] =>
[mea_commodity] => 8463
[commodity_cls] => IT
[delegate_usrid] => 877
[wf_status_step1] => 2
[wf_status_step2] => 1
[wf_status_step3] => 0
[wf_status_step4] => 0
[wf_status_step5] => 0
答案 0 :(得分:6)
一个较短的版本,可以找到值为1的所有键,以'wf_status_step'开头
$keys = array_filter(array_keys($array,1),function($key){
return stripos($key,'wf_status_step') === 0;
});
答案 1 :(得分:0)
长答案
foreach($your_array as $key=>$value)
{
if(strpos($key, 'f_status_step') !== FALSE) // will check for existence of "f_status_step" in the keys
{
if($value == 1) // if the value of that key is 1
{
// this is your target item in the array
}
}
}
答案 2 :(得分:0)
您可以迭代数组中的键以查找与您的模式匹配的所有键,并同时检查关联的值。像这样:
<?php
$found_key = null;
foreach(array_keys($my_array) as $key) {
if(strpos($key, "wf_status_step") === 0) {
//Key matches, test value.
if($my_array[$key] == 1) {
$found_key = $key;
break;
}
}
}
if( !is_null($found_key) ) {
//$found_key is the one you're looking for
} else {
//Not found.
}
?>
如果您想要更复杂地匹配密钥,可以使用正则表达式。
您还可以使用其他一些答案中显示的foreach($my_array as $key=>$value)
机制,而不是使用array_keys
。
答案 3 :(得分:0)
foreach ($array_name as $key => $value) {
if (strpos($key, 'wf_status_step') === 0) {
if ($value == 1) {
// do something
}
}
}
答案 4 :(得分:0)
试试这个
$wf_status_array = array();
foreach ($array as $key => $value) {
if($value === 1 && preg_match_all('~^wf_status_step[0-9]+$~',$key,$res)){
$key = $res[0][0];
$wf_status_array[$key] = $array[$key];
}
}
print_r($wf_status_array)