PHP - 按字符串给出的名称查找数组

时间:2022-08-08 21:31:10

I've got some arrays like this
$something = array('foo' => 'bar');

我有一些这样的数组$ something = array('foo'=>'bar');

Now how can I get the content of $something? I want to use this method to retrieve values from arrays but can't work out how to find an array with only it's name given as a string.

现在我如何获得$ something的内容?我想使用此方法从数组中检索值,但无法找到如何查找仅以字符串形式给出的数组的数组。

getArrayData($array,$key){
    // $array == 'something';
    // $key == 'foo';
    // this should return 'bar'
}

EDIT:

编辑:

I abstracted this too much maybe, so here is the full code:

我可能过多地抽象了这个,所以这里是完整的代码:

class Config {
public static $site = array(
    'ssl' => 'true',
    'charset' => 'utf-8',
    // ...
);

public static $menu = array(
    'home' => '/home',
    '/hub' => '/hub',
    // ...
);

public static function get($from, $key){
    return self::$from[$key];
    }

public static function __callStatic($method, $key){
    return self::get($method,$key);
    }
}

In the end the configuration should be accessible from within the whole app by using Config::site('charset') to return 'utf-8'

最后,通过使用Config :: site('charset')返回'utf-8',可以从整个应用程序中访问配置

3 个解决方案

#1


1  

You can use Variable-Variables

您可以使用变量变量

<?php
$something = array('foo' => 'bar');
$key="foo";
$arrayName="something";

echo getArrayData($$arrayName,$key);   // Notice the use of $$

function getArrayData($array,$key){
  return isset($array[$key])? $array[$key] : NULL ;
}

Fiddle

小提琴

#2


0  

$array == 'something' doesn't mean much, you can easily check the array keys and return the value if the key exists:

$ array =='something'并不重要,你可以轻松检查数组键,如果键存在则返回值:

function getArrayData($array,$key){
  if(isset($array[$key])) return $array[$key];
  else return "";
}

#3


0  

You should pass the array itself as parameter instead of the name. Then you can just return the value by the given key:

您应该将数组本身作为参数而不是名称传递。然后你可以通过给定的键返回值:

function getArrayData($array,$key){
    return $array[$key];
}

#1


1  

You can use Variable-Variables

您可以使用变量变量

<?php
$something = array('foo' => 'bar');
$key="foo";
$arrayName="something";

echo getArrayData($$arrayName,$key);   // Notice the use of $$

function getArrayData($array,$key){
  return isset($array[$key])? $array[$key] : NULL ;
}

Fiddle

小提琴

#2


0  

$array == 'something' doesn't mean much, you can easily check the array keys and return the value if the key exists:

$ array =='something'并不重要,你可以轻松检查数组键,如果键存在则返回值:

function getArrayData($array,$key){
  if(isset($array[$key])) return $array[$key];
  else return "";
}

#3


0  

You should pass the array itself as parameter instead of the name. Then you can just return the value by the given key:

您应该将数组本身作为参数而不是名称传递。然后你可以通过给定的键返回值:

function getArrayData($array,$key){
    return $array[$key];
}