Nested Array with one foreach Loop?
I need to have access to a array which looks like this.
Array
(
[0] => Array
(
[54] => Array
(
[test] => 54
[tester] => result
)
)
)
for开发者_如何转开发each($array as $key=>$value)
{
echo $key;// prints 0
echo $value;// prints Array
/*
now i can iterate through $value but i dont want it solve that way example:
foreach($value as $k=>$v)
{
echo $k;//prints test
echo $v; //prints 54
}
*/
}
How can iterate just once ? to get the values of test and tester? I hope i could explain my problem clear
Use SPL's RecursiveDirectoryIterator
$iterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator($array),
RecursiveIteratorIterator::SELF_FIRST);
foreach($iterator as $key => $val) {
if($key === 'test' || $key === 'tester') {
echo "$key = $val \n";
}
}
This will find all array elements with a value of either test or tester, regardless of where it appears in the multidimensional array. If you have to narrow it to a specific depth in the array, you can match against $iterator->getDepth()
.
You can also put the if condition into the method body of a FilterIterator's accept() method, e.g.
class TestFilter extends FilterIterator
{
public function accept()
{
return ($this->key() === 'test' || $this->key() === 'tester');
}
}
and then wrap the iterator in it before foreach
ing it, e.g.
$iterator = new TestFilter($iterator); // wrap iterator from first example
foreach($iterator as $key => $val) {
echo "$key = $val \n";
}
Further reading:
- Introduction to SPL
You could use an anonymous function to list the items. This will use recursion every time an array is encountered as an element:
array_walk_recursive($array, create_function('$item, $key',
'echo "$key => $item<br />";'
));
Or when using PHP 5.3:
array_walk_recursive($array, function($item, $key) {
echo "$key => $item<br />";
});
This will be faster (and more readable) than create_function(). However this construct is only available in PHP 5.3 and up.
Both will output:
test => 54
tester => result
Which is exactly what you want, I believe.
This would only work for this specific array:
foreach($array[0][54] as $key=>$value)
{
echo $key;// prints test and tester
echo $value;// prints 54 and result
}
精彩评论