Jump to content

[SOLVED] I need help shiftng an array


Salis

Recommended Posts

I'm having a little trouble writing a script that reorders an array. For an example, let's say I have the following array:

 

Blue

Red

White

Yellow

Black

 

Now, what I want to do is move "Yellow" before "Red" I know that "Yellow" will now take the place of "Red" and 1 should be subtracted to the index of each color until the value "Yellow" used to hold.

 

0 = Blue

1 = Red

2 = White

3 = Yellow

4 = Black

 

I'm guessing any way, the process would be like this:

 

0 + 0

1 = 3

2 - 1

3 - 1

4 - 0

 

This should shift the array to look like:

 

Blue

Yellow

Red

White

Black

 

or is there an easier way?

 

Thanks

Link to comment
Share on other sites

People can to this very easily. If we look at

 

0 - Blue

1 - Red

2 - White

3 - Yellow

4 - Black

 

And want to move Yellow before Black we know that the list will look like

 

0 - Blue

1 - Yellow

2 - Red

3 - White

4 - Black

 

But to do this in an array, I'd have to list all colors as a key, then their integer as a value. Then add 1 to the array_value up to the Yellows old value.. if that makes any since.... so

 

array('balck'=>0, 'red'=>1, 'white'=>2, 'yellow'=>3, 'black'=>4)... I don't really know, thinking out loud here. Maybe one of you can come up with something

 

Or what if I assign the colors a number and list the values like so.

array(0=>0, 1=>2, 2=>3, 3=>2, 4=>4)

 

the keys are the original order and the values are the new number... But I still need a way to add 1...

 

I hope I'm not confusing any one.

Link to comment
Share on other sites

See:

http://grady.us/temp/colors.php

 

<?php
$colors = array('Blue', 'Red', 'White', 'Yellow', 'Black');
$move = 'Yellow';
$before = 'Red';

//Remove the color you want to move.
unset($colors[array_search($move, $colors)]);

//Slice out an array from the spot you want to put the color until the end.
$endHalf = array_slice($colors, array_search($before, $colors));

//Take out the first half
$firstHalf = array_slice($colors, 0, (count($colors)-count($endHalf)));

//Assemble the new array
$colors = array_merge($firstHalf, array($move), $endHalf);
?>

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.