Reputation: 11
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.
$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, i.e.,
$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:
$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.
Upvotes: 1
Views: 830
Reputation: 1785
I believe this will work if you save $object->$type as it's own variable, then access that variable to go deeper in the array.
Upvotes: 1