Created
February 15, 2016 16:10
-
-
Save useless-stuff/0ae870b1606134a07c0b to your computer and use it in GitHub Desktop.
PHP - Recursive iterator iterator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$userInput = array( | |
'user' => array( | |
'name' => 'Mario', | |
'surname' => 'Rossi', | |
'address' => array( | |
'home' => 'via di qui, 23', | |
'work' => 'wherever plaza', | |
) | |
), | |
'accounts' => array( | |
'twitter' => '@mariorossi', | |
'linkedin' => 'http://linkedin.com/mario_rossi', | |
'skype' => 'mario.rossi' | |
) | |
); | |
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($userInput)); | |
// Get one dimensional array | |
print_r(iterator_to_array($iterator)); | |
// output | |
/* | |
[ | |
{ | |
name: "Mario", | |
surname: "Rossi", | |
home: "via di qui, 23", | |
work: "wherever plaza", | |
twitter: "@mariorossi", | |
linkedin: "http://linkedin.com/mario_rossi", | |
skype: "mario.rossi" | |
} | |
] | |
*/ | |
$output = array(); | |
foreach($iterator as $key => $value){ | |
$output[$key] = $key. ' : ' . $value. PHP_EOL; | |
echo nl2br($output[$key]); | |
} | |
// output | |
/* | |
name : Mario | |
surname : Rossi | |
home : via di qui, 23 | |
work : wherever plaza | |
twitter : @mariorossi | |
linkedin : http://linkedin.com/mario_rossi | |
skype : mario.rossi | |
*/ | |
/** | |
* Class ServerList | |
*/ | |
class ServerList extends RecursiveArrayIterator{ | |
} | |
/** | |
* Class ServerListManager | |
*/ | |
class ServerListManager extends RecursiveIteratorIterator{ | |
} | |
$serverList = new ServerList( | |
array( | |
'server_01' => array( | |
'location' => 'eu', | |
'availability' => 1, | |
'name' => 'chopin01', | |
'services' => array( | |
'http' => 80, | |
'ssh' => 22, | |
) | |
), | |
'server_02' => array( | |
'location' => 'us', | |
'availability' => 1, | |
'name' => 'mozart01', | |
'services' => array( | |
'http' => 80, | |
'ssh' => 22, | |
), | |
), | |
'server_03' => array( | |
'location' => 'eu', | |
'availability' => 1, | |
'name' => 'chopin02', | |
'services' => array( | |
'http' => 80, | |
'ssh' => 22, | |
) | |
) | |
) | |
); | |
$iterator = new ServerListManager($serverList); | |
$output = array(); | |
foreach($iterator as $key => $value){ | |
$output[$key] = $key. ' : ' . $value. PHP_EOL; | |
echo nl2br($output[$key]); | |
} | |
// Output: | |
/* | |
location : eu | |
availability : 1 | |
name : chopin01 | |
http : 80 | |
ssh : 22 | |
location : us | |
availability : 1 | |
name : mozart01 | |
http : 80 | |
ssh : 22 | |
location : eu | |
availability : 1 | |
name : chopin02 | |
http : 80 | |
ssh : 22 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment