and I am doing foreach loops on this, and I happen to be looking at $arr[‘val3’][‘val3.2’][‘val3.2.1’], is it possible to return the ‘path’ I took through the array, even to another array if necessary, so I’d get something like:
Does that make sense? I’m basically parsing an array and I need to use the keys and values (where !is_array) in SoapClient requests and this seems like the best way I can think of, if only I could easily get that path.
Potentially, yes. I’m trying to write something myself now. It’s close but not quite there. I’m a bit embarrassed to post it right now, but if I’m successful then I’ll post it for people to pull apart
I was confused by the “i’m looking at” bit, if you’re looking at it then you know where you are, as opposed to finding something and wanting to know where you found it. Anyway, my version, hope it helps.
It works as I expected, but the problem now is that I can’t use the returned information in the way that I wanted to. When I get “->val3->val3.2->val3.2.1” I want to put that in a SoapClient object as $params->val3->val3.2->val3.2.1 = ‘special’ but what’s happening instead is that $params->“val3->val3.2->val3.2.1” = ‘special’ instead, which isn’t right at all.
Can’t work out a solution at the moment. Any ideas?
No, because while it does convert the array to an object, the sub-arrays (or whatever you call them) remain as arrays, so you get
public 'params' =>
object(stdClass)[2]
public 'val1' => int 1
public 'val2' => int 2
public 'val3' =>
array
'val3.1' => int 1
'val3.2' =>
array
...
'val3.3' => int 3
public 'val4' => int 4
I suppose there’s the posibility of casting each… could try that I suppose…
If you need to merge these key/value paths onto an existing object, then this won’t work. If that’s what you need, let me know. But otherwise, deep casting the array to an object is the simplest way.
function deepCastArrayToObject($arr) {
$obj = new stdClass;
foreach ($arr as $key => $val) {
// $key must be scalar, beware of certain iterators
$obj->$key = is_array($val) ?
deepCastArrayToObject($val) : $val;
}
return $obj;
}