Jump to content

reposition array element


danthemilk

Recommended Posts

$staffArray = array();
$result = mysql_query("SELECT * FROM staff ORDER BY SUBSTRING_INDEX(name, ' ', -1) ASC");
while($row = mysql_fetch_assoc($result)) {
	array_push($staffArray, array( $row['name'] , $row['title'] , $row['office'] , $row['bio'] , $row['contact'] , $row['imageURL'] ));
}
for($i = 0; $i < sizeof($staffArray); $i++) {
	if($staffArray[$i][0] == 'List Topper') {
		// how can I move this element in the array to $staffArray[0]
	}
}

 

any help with this would be appreciated. It seems like it should be simple but I'm having a hard time with it. I just need to check for a certain name and then move it to the first position in the array.

Link to comment
https://forums.phpfreaks.com/topic/164980-reposition-array-element/
Share on other sites

try:

$staffArray = array();
   $result = mysql_query("SELECT * FROM staff ORDER BY SUBSTRING_INDEX(name, ' ', -1) ASC");
   while($row = mysql_fetch_assoc($result)) {
      array_push($staffArray, array( $row['name'] , $row['title'] , $row['office'] , $row['bio'] , $row['contact'] , $row['imageURL'] ));
   }
   for($i = 0; $i < sizeof($staffArray); $i++) {
      if($staffArray[$i][0] == 'List Topper') {
         list($row) = array_slice($staffArray,$i,1);
         array_unshift($staffArray,$row);
      }
   }

Thanks a ton fellas. I ended up doing it like this, because your solution seemed to cause an infinite loop or something:

 

$result = mysql_query("SELECT * FROM staff ORDER BY SUBSTRING_INDEX(name, ' ', -1) ASC");
while($row = mysql_fetch_assoc($result)) {
	array_push($staffArray, array( $row['name'] , $row['title'] , $row['office'] , $row['bio'] , $row['contact'] , $row['imageURL'] ));
}

for($i = 0; $i < sizeof($staffArray); $i++) {
	if($staffArray[$i][0] == 'Top of List') {
		$shiftIndex = $i;
	}
}
    list($row) = array_slice($staffArray,$shiftIndex,1);
    array_unshift($staffArray,$row);

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.