有没有办法动态访问多维PHP数组?

发布于 2025-01-10 09:43:57 字数 967 浏览 1 评论 0原文

有没有办法动态访问PHP多维数组(特定索引)?

例如,假设我想访问以下位置的值:

$array[1]['children'][0]['children'][2]['settings']['price']

是否有一个函数可以通过仅获取索引(分别为 1、0 和 2)来返回该值?并且无论有 3 个值(1、0 和 2)还是更多,它都有效。

例如,我们调用函数“getArrayValue()”,我们可以像这样:

getArrayValue('1,0,2')

这应该返回 $array[1]['children'][0]['children'][2]['country']['city']

或如果有 2 个值 getArrayValue('1,0') 应该返回 $array[1]['children'][0]['country']['city']

所以基本上,我面临的问题是需要帮助动态构建查询以获取数组值...

或者如果有办法转换像$array[1]['children'][0]['country']['city']这样的字符串 并评估它以从数组本身获取该值?

解释我的问题的另一种方法:

$arrayIndex = "[1]['children'][0]";
$requiredValue = $array[1] . $arrayIndex . ['country']['city'];

//// so $requiredValue should output the same value as the below line would:
$array[1]['children'][0]['children'][2]['country']['city'];

有办法实现这一点吗?

Is there a way to access a PHP multidimensional array (specific index) dynamically?

So for example, say I want to access a value at:

$array[1]['children'][0]['children'][2]['settings']['price']

Can there be a function which returns this value by just getting index (1, 0 and 2 respectively)? and in a way that it works whether there are 3 values (1, 0 and 2) or more.

SO for example , we call function "getArrayValue()" and we can it like so:

getArrayValue('1,0,2')

this should return
$array[1]['children'][0]['children'][2]['country']['city']

or in case of 2 values
getArrayValue('1,0')
should return
$array[1]['children'][0]['country']['city']

so basically, the issue I am facing is needing help with dynamically building the query to get array value...

Or if there is a way to convert a string like $array[1]['children'][0]['country']['city'] and evaluate it to get this value from the array itself?

Another way to explain my problem:

$arrayIndex = "[1]['children'][0]";
$requiredValue = $array[1] . $arrayIndex . ['country']['city'];

//// so $requiredValue should output the same value as the below line would:
$array[1]['children'][0]['children'][2]['country']['city'];

Is there a way to achieve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

别理我 2025-01-17 09:43:57

在您的情况下,您将需要这样的东西:

<?php
  

function getArray($i, $j, $k, $array) {
    if (isset($array[$i]['children'][$j]['children'][$k]['country']['city']))
    {
        return $array[$i]['children'][$j]['children'][$k]['country']['city'];
    }
}

$array[0]['children'][0]['children'][0]['country']['city'] = "some value";
$array[0]['children'][0]['children'][1]['country']['city'] = "another";
$array[0]['children'][1]['children'][1]['country']['city'] = "another one";
.
.
.
etc


echo getArray(0,0,0, $array) . "\n"; // output -> "some value"
echo getArray(0,0,1, $array) . "\n"; // output -> "another"
echo getArray(0,1,1, $array) . "\n"; // output -> "another one"

另一件要记住的事情是您调用了仅传递一个参数的函数。而你的多维数组至少需要三个。

getArrayValue('1,0,2')

您必须考虑到您调用的函数仅传递一个参数。即使有逗号。但它实际上是一个字符串。

getArrayValue(1,0,2) //not getArrayValue('1,0,2') == string 1,0,2

如果您想传递两个值,则必须至少添加一个 if 来控制您希望函数在这种情况下执行的内容。类似于:

  function getArray($i, $j, $k, $array) {
    if($k==null){
        if(isset($array[$i]['children'][$j]['country']['city'])){
            return $array[$i]['children'][$j]['country']['city']; //
        }
    } else {
        if(isset($array[%i]['children'][$j]['children'][$k]['country']['city'])){
            return $array[$i]['children'][$j]['children'][$k]['country']['city'];
        }
    }
}

getArray(0,0,null, $array) 
getArray(0,0,1, $array) 

对于最后一个问题,您可以使用 eval() 函数得到。但我认为这不是一个好主意。至少不推荐。示例:

echo ' someString ' . eval( 'echo $var = 15;' );

您可以查看文档: https://www.php.net/ Manual/es/function.eval.php

编辑
我忘了提及您还可以使用默认参数。就像这里一样。

<?php

$array[0]['children'][0]['children'][0]['country']['city'] = "some value";
$array[0]['children'][0]['children'][1]['country']['city'] = "another";
$array[0]['children'][1]['children'][1]['country']['city'] = "another one";

function getArray($array,$i, $j, $k = null) {
    if($k==null){
        echo 'getArray called without $k argument';
        echo "\n";
    } 
    else{
        echo 'getArray called with $k argument';
        echo "\n";
    }
   
}

getArray($array,0,0);    //here you call the function with only 3 arguments, instead of 4
getArray($array,0,0,1);

在这种情况下 $k 是可选的。如果省略它,默认值将为空。此外,您还必须考虑到函数可以使用类似于分配变量的语法来定义参数的默认值。仅当不指定参数时才使用默认值;特别要注意的是,传递 null 并不分配默认值。

<?php
function makecoffee($type = "cappuccino"){
    return "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");

上面的示例将输出:

Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.

您可以在此处阅读更多相关信息: https:// www.php.net/manual/en/functions.arguments.php

In your case you will need something like this:

<?php
  

function getArray($i, $j, $k, $array) {
    if (isset($array[$i]['children'][$j]['children'][$k]['country']['city']))
    {
        return $array[$i]['children'][$j]['children'][$k]['country']['city'];
    }
}

$array[0]['children'][0]['children'][0]['country']['city'] = "some value";
$array[0]['children'][0]['children'][1]['country']['city'] = "another";
$array[0]['children'][1]['children'][1]['country']['city'] = "another one";
.
.
.
etc


echo getArray(0,0,0, $array) . "\n"; // output -> "some value"
echo getArray(0,0,1, $array) . "\n"; // output -> "another"
echo getArray(0,1,1, $array) . "\n"; // output -> "another one"

Another thing to keep in mind is that you have called the function passing only one parameter. And your multidimensional array needs at least three.

getArrayValue('1,0,2')

You have to take into account that you have called the function passing only one parameter. Even if there were commas. But it's actually a string.

getArrayValue(1,0,2) //not getArrayValue('1,0,2') == string 1,0,2

If you want to pass two values, you would have to put at least one if to control what you want the function to execute in that case. Something like:

  function getArray($i, $j, $k, $array) {
    if($k==null){
        if(isset($array[$i]['children'][$j]['country']['city'])){
            return $array[$i]['children'][$j]['country']['city']; //
        }
    } else {
        if(isset($array[%i]['children'][$j]['children'][$k]['country']['city'])){
            return $array[$i]['children'][$j]['children'][$k]['country']['city'];
        }
    }
}

getArray(0,0,null, $array) 
getArray(0,0,1, $array) 

For the last question you can get by using the eval() function. But I think it's not a very good idea. At least not recommended. Example:

echo ' someString ' . eval( 'echo $var = 15;' );

You can see the documentation: https://www.php.net/manual/es/function.eval.php

edit:
I forgot to mention that you can also use default arguments. Like here.

<?php

$array[0]['children'][0]['children'][0]['country']['city'] = "some value";
$array[0]['children'][0]['children'][1]['country']['city'] = "another";
$array[0]['children'][1]['children'][1]['country']['city'] = "another one";

function getArray($array,$i, $j, $k = null) {
    if($k==null){
        echo 'getArray called without $k argument';
        echo "\n";
    } 
    else{
        echo 'getArray called with $k argument';
        echo "\n";
    }
   
}

getArray($array,0,0);    //here you call the function with only 3 arguments, instead of 4
getArray($array,0,0,1);

In that case $k is optional. If you omit it, the default value will be null. Also you have to take into account that A function may define default values for arguments using syntax similar to assigning a variable. The default is used only when the parameter is not specified; in particular, note that passing null does not assign the default value.

<?php
function makecoffee($type = "cappuccino"){
    return "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");

The above example will output:

Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.

You can read more about that here: https://www.php.net/manual/en/functions.arguments.php

幻梦 2025-01-17 09:43:57

我发现 @Dac2020 的答案太不灵活,对未来的研究人员没有帮助。事实上,问题中过于具体/利基的要求并不能让本页对未来的研究人员有很大帮助,因为处理逻辑与数组结构紧密耦合。

也就是说,我尝试构建一个函数来构建检查密钥是否存在和 DRY 原则的最佳实践,希望未来的研究人员能够根据自己的需要轻松修改它。

在自定义函数中,第一步是将 csv 拆分为数组,然后按照提问者的指示将静态键交织在动态键之间。在更一般的用例中,所有键都将传递到函数中,从而无需准备键数组。

正如@MarkusAO 在问题下的评论中正确提到的那样,这个问题几乎与 Convert 点语法如“this.that.other”重复" 到 PHP 中的多维数组

代码:(演示

function getValue($haystack, $indexes) {
    $indices = explode(',', $indexes);
    $finalIndex = array_pop($indices);
    $keys = [];
    foreach ($indices as $keys[]) {
        $keys[] = 'children';
    }
    array_push($keys, $finalIndex, 'country', 'city');
    //var_export($keys);

    foreach ($keys as $level => $key) {
        if (!key_exists($key, $haystack)) {
            throw new Exception(
                sprintf(
                    "Path attempt failed for [%s]. No `%s` key found on levelIndex %d",
                    implode('][', $keys),
                    $key,
                    $level
                )
            );
        }
        $haystack = $haystack[$key];
    }
    return $haystack;
}

$test = [
    [
        'children' => [
            [
                'children' => [
                    [
                        'country' => [
                            'city' => 'Paris',
                         ]
                    ],
                    [
                        'country' => [
                            'city' => 'Kyiv',
                         ]
                    ]
                ]
            ]
        ]
    ],
    [
        'children' => [
            [
                'country' => [
                    'city' => 'New York',
                ]
            ],
            [
                'country' => [
                    'city' => 'Sydney',
                ]
            ]
        ]
    ]
];

$result = [];
try {
    $result['0,0,0'] = getValue($test, '0,0,0');
    $result['1,0'] = getValue($test, '1,0');
    $result['1,0,0'] = getValue($test, '1,0,0');
} catch (Exception $e) {
    echo $e->getMessage() . "\n---\n";
}
var_export($result);

输出:

Path attempt failed for [1][children][0][children][0][country][city]. No `children` key found on levelIndex 3
---
array (
  '0,0,0' => 'Paris',
  '1,0' => 'New York',
)

I find @Dac2020's answer to be too inflexible to be helpful to future researchers. In fact, the overly specific/niche requirements in the question does not lend this page to being very helpful for future researchers because the processing logic is tightly coupled to the array structure.

That said, I've tried to craft a function that builds best practices of checking for the existence of keys and D.R.Y. principles in the hope that future researchers will be able to easily modify it for their needs.

Inside the custom function, the first step is to split the csv into an array then interweave the static keys between the dynamic keys as dictated by the asker. In more general use cases, ALL keys would be passed into the function thus eliminating the need to prepare the array of keys.

As correctly mentioned by @MarkusAO in a comment under the question, this question is nearly a duplicate of Convert dot syntax like "this.that.other" to multi-dimensional array in PHP.

Code: (Demo)

function getValue($haystack, $indexes) {
    $indices = explode(',', $indexes);
    $finalIndex = array_pop($indices);
    $keys = [];
    foreach ($indices as $keys[]) {
        $keys[] = 'children';
    }
    array_push($keys, $finalIndex, 'country', 'city');
    //var_export($keys);

    foreach ($keys as $level => $key) {
        if (!key_exists($key, $haystack)) {
            throw new Exception(
                sprintf(
                    "Path attempt failed for [%s]. No `%s` key found on levelIndex %d",
                    implode('][', $keys),
                    $key,
                    $level
                )
            );
        }
        $haystack = $haystack[$key];
    }
    return $haystack;
}

$test = [
    [
        'children' => [
            [
                'children' => [
                    [
                        'country' => [
                            'city' => 'Paris',
                         ]
                    ],
                    [
                        'country' => [
                            'city' => 'Kyiv',
                         ]
                    ]
                ]
            ]
        ]
    ],
    [
        'children' => [
            [
                'country' => [
                    'city' => 'New York',
                ]
            ],
            [
                'country' => [
                    'city' => 'Sydney',
                ]
            ]
        ]
    ]
];

$result = [];
try {
    $result['0,0,0'] = getValue($test, '0,0,0');
    $result['1,0'] = getValue($test, '1,0');
    $result['1,0,0'] = getValue($test, '1,0,0');
} catch (Exception $e) {
    echo $e->getMessage() . "\n---\n";
}
var_export($result);

Output:

Path attempt failed for [1][children][0][children][0][country][city]. No `children` key found on levelIndex 3
---
array (
  '0,0,0' => 'Paris',
  '1,0' => 'New York',
)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文