Php 将字符串转换为数组地址
我动态生成了数组Php 将字符串转换为数组地址,php,arrays,Php,Arrays,我动态生成了数组$array[],它可能是多维的,并且我有一个返回字符串的函数,该字符串包含数组中的地址(现有的)。我的问题是:如何创建字符串$a='array[1]或将其转换为地址$array[1] 例如: $array = [1,2,3,4]; $string = 'array[2]'; function magic($array, $string){ //some magic happens return $result; $result = magic($array, $string
$array[]
,它可能是多维的,并且我有一个返回字符串的函数,该字符串包含数组中的地址(现有的)。我的问题是:如何创建字符串$a='array[1]
或将其转换为地址$array[1]
例如:
$array = [1,2,3,4];
$string = 'array[2]';
function magic($array, $string){
//some magic happens
return $result;
$result = magic($array, $string);
echo $result;
// and 3 is displayed;
是否已经有函数可以执行此操作?有可能这样做吗 此代码是对精彩项目的修改:
函数magic($array,$path,$default=null)
{
if(false==$pos=strpos($path,[')){
返回$array;
}
$value=$array;
$currentKey=null;
对于($i=$pos,$c=strlen($path);$i<$c;$i++){
$char=$path[$i];
如果('['==$char){
如果(null!=$currentKey){
抛出新的\InvalidArgumentException(sprintf('格式错误的路径,位置%d.,$i处出现意外的“[”);
}
$currentKey='';
}elseif(']'==$char){
如果(null==$currentKey){
抛出新的\InvalidArgumentException(位置%d.,$i处的sprintf('格式错误的路径,意外的“]”);
}
如果(!is_array($value)| |!array_key_存在($currentKey,$value)){
返回$default;
}
$value=$value[$currentKey];
$currentKey=null;
}否则{
如果(null==$currentKey){
抛出新的\InvalidArgumentException(sprintf('格式错误的路径,位置%d.'处意外出现“%s”,$char,$i));
}
$currentKey.=$char;
}
}
如果(null!=$currentKey){
抛出new\InvalidArgumentException(sprintf('格式错误的路径。路径必须以“]”结尾);
}
返回$value;
}
回声魔法([1,2,3,4],“数组[2]”)3.
也可以修改它以返回引用,只需在它上洒上一些符号:)它应该是$string=&$array[2];这是一个引用:
echo eval(“$”.$string)
eval似乎是正确的方法,并且可能会使用引用,以便您也可以更改值。为什么您的函数会返回这样的字符串,而不仅仅是索引值?这可能是因为它是用户输入的。否则,他可以只返回一个推荐人。
function magic($array, $path, $default = null)
{
if (false === $pos = strpos($path, '[')) {
return $array;
}
$value = $array;
$currentKey = null;
for ($i = $pos, $c = strlen($path); $i < $c; $i++) {
$char = $path[$i];
if ('[' === $char) {
if (null !== $currentKey) {
throw new \InvalidArgumentException(sprintf('Malformed path. Unexpected "[" at position %d.', $i));
}
$currentKey = '';
} elseif (']' === $char) {
if (null === $currentKey) {
throw new \InvalidArgumentException(sprintf('Malformed path. Unexpected "]" at position %d.', $i));
}
if (!is_array($value) || !array_key_exists($currentKey, $value)) {
return $default;
}
$value = $value[$currentKey];
$currentKey = null;
} else {
if (null === $currentKey) {
throw new \InvalidArgumentException(sprintf('Malformed path. Unexpected "%s" at position %d.', $char, $i));
}
$currentKey .= $char;
}
}
if (null !== $currentKey) {
throw new \InvalidArgumentException(sprintf('Malformed path. Path must end with "]".'));
}
return $value;
}
echo magic([1,2,3,4], 'array[2]'); // 3