0

我有以下数组。我想得到具有“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
4

5 回答 5

6

一个较短的版本,它将找到所有以 'wf_status_step' 开头的值为 1 的键

$keys = array_filter(array_keys($array,1),function($key){
    return stripos($key,'wf_status_step') === 0;
});
于 2013-08-07T18:05:07.030 回答
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)
于 2013-08-07T18:12:20.127 回答
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
     }
  }
}
于 2013-08-07T17:49:00.110 回答
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.

于 2013-08-07T17:49:36.130 回答
0
foreach ($array_name as $key => $value) {
  if (strpos($key, 'wf_status_step') === 0) {
    if ($value == 1) {
      // do something
    }
  }
}
于 2013-08-07T17:49:56.293 回答