问题
I have this kind of array:
Array ( [data] => Array ( [0] => Array ( [name] => Lskdjlkdsfj [start_time] => 2013-06-12 [timezone] => Europe/Rome [location] => Rome, Lazio [id] => 592087844156650 [rsvp_status] => attending ) ) [paging] => Array ( [previous] => https://graph.facebook.com/100004042705860/events?limit=25&since=1370995200&__paging_token=592087844156650&__previous=1 [next] => https://graph.facebook.com/100004042705860/events?limit=25&until=1370995200&__paging_token=592087844156650 ) )
To get the data I am doing so:
foreach ($fb_events as $data) {
foreach ($data as $fb_event_data) {
echo $fb_event_data['name'];
echo $fb_event_data['start_time'];
}
}
Is this the best way to do it, using a double foreach? Is there a better way to loop into an array of an array? This one is working. I am just wondering if I am doing it the "right" way!
回答1:
If the top level array only has a single element then this can be simplified as
foreach ($fb_events["data"] as $fb_event_data) {
echo $fb_event_data['name'];
echo $fb_event_data['start_time'];
}
回答2:
While there is nothing wrong with using nested loops. In some cases you might want to solve looping in a more elegant way. Take a look at PHP's RecursiveArrayIterator and RecursiveIteratorIterator classes for that.
$foo = array(
'data' => array(
'name' => 'Lskdjlkdsfj',
'start_time' => '2013-06-12',
'paging' => array(
'previous' => 'some-url'
)
)
);
$it = new RecursiveIteratorIterator( new RecursiveArrayIterator($foo) );
foreach ($it as $key => $val) {
echo $key . ":" . $val . "\n";
}
name:Lskdjlkdsfj
start_time:2013-06-12
previous:some-url
回答3:
Nested loops are no more "right" or "wrong" than nested arrays are. That is to say, it depends entirely upon your data and its meaning.
If you end up with five levels of nested loops, you might want to reconsider the structure of your code. But I don't think one level of nesting is ipso facto a problem.
来源:https://stackoverflow.com/questions/17071233/php-avoid-double-foreach-when-looping-into-an-array-of-an-array