Jump to content

A better way of looping using foreach and switch


AdRock

Recommended Posts

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:
		}
		
	}
}

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.