
php
🚀
note2self
🚀
Quick way to traverse a nested php arrray
The RecursiveIteratorIterator makes it super easy to traverse a nested array.
Here is an example though the docs are pretty clear there. For me it was in a class so I defined the array keys at the top of the Class
protected $merged_profile_options = [];
protected $data_values = [
'browser' => null,
'name' => null,
'version' => null,
'platform' => null,
'base_url' => null,
'repo' => null,
'filename' => null,
'branch' => null,
'status' => null,
'user_uuid' => null,
'remote_job_id' => null,
'job_id' => null,
];
Then later on iterated over that array.
protected function setAllDataValues() {
$traverse = new \RecursiveIteratorIterator(
new \RecursiveArrayIterator($this->merged_profile_options));
foreach($traverse as $key=>$value)
{
if(array_key_exists($key, $this->data_values))
{
$this->setDataValues($key, $value);
}
}
}
public function setDataValues($key, $value)
{
$this->data_values[$key] = $value;
}
Super easy. This array was 4 levels deep.