Jump to content

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.

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.