AdRock Posted August 23, 2014 Share Posted August 23, 2014 (edited) 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: } } } Edited August 23, 2014 by AdRock Quote Link to comment 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. Quote Link to comment Share on other sites More sharing options...
Solution Barand Posted August 23, 2014 Solution Share Posted August 23, 2014 $data = array(); foreach($rows as $row) { $data[$row['type']][$row['archived']][] = $row; } 1 Quote Link to comment 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? Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.