使用PHP使用索引部分字符串查找数组值


Array value find using index partial string using PHP

我有下面的数组。我想得到具有"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

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

$keys = array_filter(array_keys($array,1),function($key){
    return stripos($key,'wf_status_step') === 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
     }
  }
}

您可以对数组中的键进行迭代,以找到与您的模式匹配的所有键,并模拟地检查关联的值。类似这样的东西:

<?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

尝试这个

   $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)
foreach ($array_name as $key => $value) {
  if (strpos($key, 'wf_status_step') === 0) {
    if ($value == 1) {
      // do something
    }
  }
}