简体   繁体   English

使用未知键访问嵌套的关联数组

[英]Accessing nested associative array with unknown keys

I am trying to access elements from a multidimensional array in an object. 我正在尝试从对象中的多维数组访问元素。 For example, let's assume there is some class Foo that has a variable called $phone that represents the multidimensional array. 例如,假设有一些Foo类具有一个名为$ phone的变量,该变量代表多维数组。

$phone -> structure will look like
Array {
  "home" Array(1) {[0] = "555-1212"},
  "work" Array(2) {[0] = "555-1234", [1] = "555=5434"},
  "other" Array(1) {[0] = "555=9090"}
}

Note: We can't assume we know the keys. 注意:我们不能假设我们知道按键。

I can access a value by giving explicit keys, ie, 我可以通过提供显式键来访问值,即

$foo->phone["home"][0]

The problem comes to when I don't explicitly know the keys and pull them from elsewhere. 问题出在我不明确知道按键并将其从其他地方拉出来的时候。 For example if $type="phone", $subtype = "home", and I want the first entry I would expect to use: 例如,如果$ type =“ phone”,$ subtype =“ home”,并且我希望使用第一个条目:

$object->$type[$subtype][0]

to get the value, but I get an error and it doesn't think it is an array. 获取值,但出现错误,并且它不认为它是数组。 I am not sure where the error is. 我不确定错误在哪里。

The next thing would be to add elements to the lowest level array. 接下来的事情是将元素添加到最低级别的数组中。 I assume the following would work, but doesn't: 我认为以下方法会起作用,但不会:

array_push($object->$type[$subtype], $value)

This mutidimensional array would allow me to store phone numbers labelled by keys in a single nested structure. 这个多维数组可让我将按键标记的电话号码存储在单个嵌套结构中。 If this is overcomplicating the issue please let me know. 如果这使问题变得过于复杂,请告诉我。 The reason I chose this structure is because the keys can be anything the user customizes. 之所以选择这种结构,是因为键可以是用户自定义的任何键。

Thanks. 谢谢。

我相信如果将$ object-> $ type保存为自己的变量,然后访问该变量以更深入数组,这将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM