AdRock Posted August 23, 2014 Share Posted August 23, 2014 Is there a nicer, cleaner more efficient and less code way of achieving this? I have an array of rows from the database and 2 of the columns could have either of 2 values which give me 4 possibilities. I want to loop through each of them and assign the row to one of 4 arrays so they are all separated out. This is what i have so far. Haven't tested it yet but the theory makes sense. if(!empty($rows)) { foreach($rows as $key => $row) { switch($row['type']) { case 'post': switch($row['archived']) { case 0: $array1[$key] = $row; break; case 1: $array2[$key] = $row; break; default: } break; case 'event': switch($row['archived']) { case 0: $array3[$key] = $row; break; case 1: $array4[$key] = $row; break; default: } break; default: } } } Link to comment https://forums.phpfreaks.com/topic/290609-a-better-way-of-looping-using-foreach-and-switch/ Share on other sites More sharing options...
Jacques1 Posted August 23, 2014 Share Posted August 23, 2014 I only see 2 arrays, not 4. Anyway, all you need to do is create a lookup table which maps each (type, archived) combination to a destination. This is typically done with an associative array: <?php $target_categories = array( 'post' => array( 0 => 'foo', 1 => 'bar', ), 'event' => array( 0 => 'qux', 1 => 'quux', ), ); Or you just store the rows in this nested structure and skip the mapping part. Link to comment https://forums.phpfreaks.com/topic/290609-a-better-way-of-looping-using-foreach-and-switch/#findComment-1488682 Share on other sites More sharing options...
Barand Posted August 23, 2014 Share Posted August 23, 2014 $data = array(); foreach($rows as $row) { $data[$row['type']][$row['archived']][] = $row; } Link to comment https://forums.phpfreaks.com/topic/290609-a-better-way-of-looping-using-foreach-and-switch/#findComment-1488685 Share on other sites More sharing options...
Jacques1 Posted August 23, 2014 Share Posted August 23, 2014 You didn't think AdRock is intelligent enough to write that down himself? Link to comment https://forums.phpfreaks.com/topic/290609-a-better-way-of-looping-using-foreach-and-switch/#findComment-1488689 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.