Jump to content

A better way of looping using foreach and switch


AdRock
Go to solution Solved by Barand,

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

Edited by AdRock
Link to comment
Share on other sites

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.