排除 PHP 中 foreach 中以“#”开头的数组键


Excluding array keys that start with '#' from foreach in PHP?

我有一个Drupal表单数组,它使用前缀"#"来指示给定的数组键包含元数据而不是实际值。如何遍历除键以"#"开头的数组元素之外的所有数组元素?

foreach( $array as $key => $value ) {
    if( $key[0] === "#" ) {
        continue;
    }
    //Do work
}

当前键以 # 开头时,您可以使用 continue 跳到循环中的下一个迭代。获取第一个字符的一种方法是使用 substr()

foreach ($array as $key => $value) {
    if (substr($key, 0, 1) === '#') continue;
    //do stuff
}

试试这个:

<?php
function deleteElements(&$v, $k) {
   global $newArray;
   if(substr($k, 0, 1) !== '#') {
      $newArray[$k] = $v;
   }
}
$arr = array('as'=>'Test','#df'=>'this will not come','gh'=>'no test','#e'=>'again!');
$newArray = array(); // this will contain non-metadata keys
array_walk( $arr, 'deleteElements' );
//$newArrayis now..
$newArray = array('as'=>'Test','gh'=>'no test');
?>

希望这有帮助。