1

这可能吗?

就像用所有具有特定前缀的变量创建一个数组?

我不需要键只是值,但我想我可以在数组上使用 array_values。

4

4 回答 4

3

如果你需要这样做,一开始可能写得不太好,但是,这里是如何做到的:)

$foobar = 'test';
$anothervar = 'anothertest';
$foooverflow = 'fo';
$barfoo = 'foobar';

$prefix = 'foo';
$output = array();
$vars = get_defined_vars();
foreach ($vars as $key => $value) {
    if (strpos($key, $prefix) === 0) $output[] = $value;
}

/*
$output = array(
    'test', // from $foobar
    'fo', // from $foooverflow
);
*/

http://php.net/manual/en/function.get-defined-vars.php

于 2012-05-15T01:27:17.817 回答
2

my eyes are bleeding a little, but I couldn't resist a one liner.

print_r(iterator_to_array(new RegexIterator(new ArrayIterator(get_defined_vars()), '/^' . preg_quote($prefix) . '/', RegexIterator::GET_MATCH, RegexIterator::USE_KEY)));
于 2012-05-15T01:50:33.490 回答
1

This, my second answer, shows how to do this without making a mess of the global scope by using a simple PHP object:

$v = new stdClass();
$v->foo = "bar";
$v->scope = "your friend";
$v->using_classes = "a good idea";
$v->foo_overflow = "a bad day";

echo "Man, this is $v->using_classes!\n";

$prefix = "foo";
$output = array();
$refl = new ReflectionObject($v);
foreach ($refl->getProperties() as $prop) {
        if (strpos($prop->getName(), $prefix) === 0) $output[] = $prop->getValue($v);
}

var_export($output);

Here's the output:

Man, this is a good idea!
array (
  0 => 'bar',
  1 => 'a bad day',
)
于 2012-05-15T02:29:58.727 回答
1

如果你在谈论全局范围内的变量,你可以这样做$GLOBALS[]

$newarray = array();

// Iterate over all current global vars 
foreach ($GLOBALS as $key => $value) {
  // And add those with keys matching prefix_ to a new array
  if (strpos($key, 'prefix_' === 0) {
    $newarray[$key] = $value;
  }
}

如果您在全局范围内有很多很多变量,那么执行起来会比手动将它们全部添加到 中要慢compact(),但输入起来会更快。

附录

我只想补充一点(尽管我怀疑你已经知道了),如果你有能力重构这段代码,你最好首先将相关变量组合到一个数组中。

于 2012-05-15T01:21:21.130 回答