PHP:使用数组在另一个多维数组中获取价值 [英] PHP: Use array to get value in another, multidimensional array

查看:61
本文介绍了PHP:使用数组在另一个多维数组中获取价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个特定于WordPress的上下文,但是我的问题更多是与PHP相关的...

This is a WordPress-specific context but my question is more PHP-related...

我发现自己处于一种奇怪的情况下,我需要使用包含正确顺序的键序列的另一个数组来获取多维数组内部的值.

I'm finding myself in an odd situation where I need to get a value deep inside a multidimensional array, using another array that contains the sequence of keys in the correct order.

所以本质上我有一个看起来像

So essentially I have an array the looks something like

[0] => 'neighborhood' [1] => 'street' [2] => 'house'

最终我需要的是

get_option( $options_id )['neighborhood']['street']['house']

因此,基本上,我需要通过使用另一个数组递归向下操作,从Options数组中获取'house'的值.

So basically I need to get the value of 'house' from the Options array by using another array to recurse down to it.

我不能做类似的事情

foreach ( $array as $value ) {
    $sequence .= '[' $value ']';
}
get_option( $options_id ) . $sequence;

因为这会将$sequence的值填充为字符串.我一直在尝试使用explode()的方法,但是没有任何运气,但是我并不是真正的PHP向导,所以我希望有一个我以前从未遇到过的明显答案.

because that would fill $sequence with the values as a string. I've been trying things with explode() without any luck, but I'm not really a PHP wizard so I'm hoping there's some kind of obvious answer that I just haven't encountered before.

我知道这很奇怪,但是任何帮助将不胜感激!

I know it's a weird situation but any help would be much appreciated!

推荐答案

您可能想创建某种帮助程序功能,在其中遍历路径的某些部分,同时跟踪您的临时结果 :

You might want to create some kind of helper function, where you iterate over parts of your path while keeping track of your temporary result:

function deep_array_get(array $path, array $subject) {

   $result = $subject;
   foreach ($path as $p) {
      $result = $result[$p];
   }

   return $result;

}

示例:

$p = ["a", "b", "c"];
$s = [1, 2, "a" => [3, 4, "b" => ["c" => 5]]];
var_dump(deep_array_get($p, $s));

// Result: int(5)

在您的确切用例中,将使用如下所示的内容:

In your exact usecase it would be used something like this:

$path = ['neighborhood', 'street', 'house'];
$subject = get_option($options_id);

$result = deep_array_get($path, $subject);

这篇关于PHP:使用数组在另一个多维数组中获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆