将字符串转换为数组的最佳方法

时间:2022-08-25 19:59:39

I have an array $AR
I have a string "set[0][p1]"

我有一个数组$ AR我有一个字符串“set [0] [p1]”

When given this string, I need the best way to access the array at $AR['set'][0]['p1']

当给出这个字符串时,我需要在$ AR ['set'] [0] ['p1']访问数组的最佳方法

I have total control on that string, so I need not to worry from injections and stuff, and I can be sure it will be well formatted. There is no way I can put the p1 inside ' to be "set[0]['p1']"

我完全控制了那个字符串,所以我不必担心注射和东西,我可以肯定它的格式很好。我无法将p1置于“被设置为”[0] ['p1']“

4 个解决方案

#1


3  

Check parse_str():

parse_str('set[0][p1]', $AR);

Oh, you want to access the index of the array... Here is my take:

哦,你想要访问数组的索引......这是我的看法:

getValue($AR, array('set', 0, 'p1'));

Or if you really must use the original string representation:

或者,如果您真的必须使用原始字符串表示:

parse_str('set[0][p1]', $keys);
getValue($AR, $keys);

Disclaimer: I haven't tested this, you might need to use array_keys() somewhere.

免责声明:我没有测试过这个,你可能需要在某处使用array_keys()。


And the helper function:

和辅助函数:

function getValue($array, $key, $default = false)
{
    if (is_array($array) === true)
    {
        settype($key, 'array');

        foreach ($key as $value)
        {
            if (array_key_exists($value, $array) === false)
            {
                return $default;
            }

            $array = $array[$value];
        }

        return $array;
    }

    return $default;
}

I would avoid regexing your way into this problem.

我会避免重新解决这个问题。

#2


3  

My try, which should be able to deal with an arbitrary amount of []s in the string:

我的尝试,应该能够处理字符串中的任意数量的[] s:

To split the string you can use preg_split.

要拆分字符串,可以使用preg_split。

$parts = preg_split('%\[?(\w+)\]?%', $string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

(More) complete code:

(更多)完整代码:

function get_value($string, $array) {
    $parts = preg_split('%\[?(\w+)\]?%', $string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

    foreach($parts as $part) {
        $array = $array[$part];
    }

    return $array;
}

$array = array('set'=>array(array('p1'=>'foo')));
$string = "set[0][p1]";

echo get_value($string, $array); // echoes 'foo'

I leave the error handling to you ;)

我把错误处理留给你;)

#3


2  

Perhaps this is crazy, but have you considered extract? It may not be the fastest solution, but it has the novelty of needing minimal code.

也许这很疯狂,但你考虑过提取物吗?它可能不是最快的解决方案,但它具有需要最少代码的新颖性。

extract( $AR );
$target = eval("\$set[0]['p1']");

The major difference (as far as input is concerned) is that you would need to pre-pend '$' to the string, and make sure that the brackets have quote marks inside.

主要区别(就输入而言)是你需要将'$'预先挂起到字符串,并确保括号内有引号。

The major benefit is that it becomes extraordinarily obvious what you're trying to accomplish, and you're using two native PHP functions. Both of these mean that the solution would be far more "readable" by those unfamiliar with your system.

主要的好处是,你想要完成的事情变得非常明显,并且你正在使用两个本机PHP函数。这两个意味着解决方案对于那些不熟悉您的系统的人来说更具“可读性”。

Oh, and you're only using two lines of code.

哦,你只使用两行代码。

#4


0  

You need something like. I'm not 100% about the "[" and "]" brackets as I've never had to run a regex on them before... if it's wrong can someone correct me??

你需要类似的东西。我不是100%关于“[”和“]”括号,因为我以前从来没有对它们运行正则表达式...如果它错了可以有人纠正我吗?

foreach(preg_split('/[\[\]]/', "set[0][p1]") as $aValue) {
    $AR[$aValue[0]][$aValue[1]][$aValue[2]] = '?';
}

#1


3  

Check parse_str():

parse_str('set[0][p1]', $AR);

Oh, you want to access the index of the array... Here is my take:

哦,你想要访问数组的索引......这是我的看法:

getValue($AR, array('set', 0, 'p1'));

Or if you really must use the original string representation:

或者,如果您真的必须使用原始字符串表示:

parse_str('set[0][p1]', $keys);
getValue($AR, $keys);

Disclaimer: I haven't tested this, you might need to use array_keys() somewhere.

免责声明:我没有测试过这个,你可能需要在某处使用array_keys()。


And the helper function:

和辅助函数:

function getValue($array, $key, $default = false)
{
    if (is_array($array) === true)
    {
        settype($key, 'array');

        foreach ($key as $value)
        {
            if (array_key_exists($value, $array) === false)
            {
                return $default;
            }

            $array = $array[$value];
        }

        return $array;
    }

    return $default;
}

I would avoid regexing your way into this problem.

我会避免重新解决这个问题。

#2


3  

My try, which should be able to deal with an arbitrary amount of []s in the string:

我的尝试,应该能够处理字符串中的任意数量的[] s:

To split the string you can use preg_split.

要拆分字符串,可以使用preg_split。

$parts = preg_split('%\[?(\w+)\]?%', $string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

(More) complete code:

(更多)完整代码:

function get_value($string, $array) {
    $parts = preg_split('%\[?(\w+)\]?%', $string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

    foreach($parts as $part) {
        $array = $array[$part];
    }

    return $array;
}

$array = array('set'=>array(array('p1'=>'foo')));
$string = "set[0][p1]";

echo get_value($string, $array); // echoes 'foo'

I leave the error handling to you ;)

我把错误处理留给你;)

#3


2  

Perhaps this is crazy, but have you considered extract? It may not be the fastest solution, but it has the novelty of needing minimal code.

也许这很疯狂,但你考虑过提取物吗?它可能不是最快的解决方案,但它具有需要最少代码的新颖性。

extract( $AR );
$target = eval("\$set[0]['p1']");

The major difference (as far as input is concerned) is that you would need to pre-pend '$' to the string, and make sure that the brackets have quote marks inside.

主要区别(就输入而言)是你需要将'$'预先挂起到字符串,并确保括号内有引号。

The major benefit is that it becomes extraordinarily obvious what you're trying to accomplish, and you're using two native PHP functions. Both of these mean that the solution would be far more "readable" by those unfamiliar with your system.

主要的好处是,你想要完成的事情变得非常明显,并且你正在使用两个本机PHP函数。这两个意味着解决方案对于那些不熟悉您的系统的人来说更具“可读性”。

Oh, and you're only using two lines of code.

哦,你只使用两行代码。

#4


0  

You need something like. I'm not 100% about the "[" and "]" brackets as I've never had to run a regex on them before... if it's wrong can someone correct me??

你需要类似的东西。我不是100%关于“[”和“]”括号,因为我以前从来没有对它们运行正则表达式...如果它错了可以有人纠正我吗?

foreach(preg_split('/[\[\]]/', "set[0][p1]") as $aValue) {
    $AR[$aValue[0]][$aValue[1]][$aValue[2]] = '?';
}