Jump to content

order a foreach based on an array in the array


dadamssg87

Recommended Posts

I'm trying to order a foreach based on a certain item in the array of an array. So like

 

<?php
foreach($room as $key => $value)
{
if($room[$key]['available'] == "Open")
{
   //code to display array
}else
{
//wait till all "Open" items are displayed and then display non-"open" items
}
}

 

anybody have any suggestions on the best way to tackle this?

<?php
$room = array(	0 => array('available' => 'Open', 'id' => 'First'), 
		1 => array('available' => 'Closed', 'id' => 'Second'), 
		3 => array('available' => 'Open', 'id' => 'Third'), 
		4 => array('available' => 'Closed', 'id' => 'Fourth'));
$code="";

foreach($room as $key => $value) {
	if($room[$key]['available'] == "Open") {
		   //code to display array
		echo "{$value['id']} - {$value['available']}<br />";
	}
	else {
		//wait till all "Open" items are displayed and then display non-"open" items
		$code.="{$value['id']} - {$value['available']}<br />";
	}
}
echo $code;
?>

 

Output:

 

First - Open

Third - Open

Second - Closed

Fourth - Closed

To sort it do this, then loop again and display:

 

foreach($room as $key => $value) {
   $available[$key] = $value['available'];
}
array_multisort($available, SORT_DESC, $room);

To output and build an array to output later:

 

foreach($room as $value) {
   if($value['available'] == "Open") {
      $open[] = $value;
   } else {
      $closed[] = $value;
   }
}

So above you can echo the $value['whatever'] stuff in the open portion and then loop through the $closed array and echo them, or you can do this and loop again:

 

$room = array_merge($open, $closed);

And then loop over that and echo.

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.