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
https://forums.phpfreaks.com/topic/68857-solved-i-need-help-shiftng-an-array/
Share on other sites

You can sort by a function usign unisort but this isn't exactly a normal function because its not based on y=mx+b where y is the final key m is some slope x is the inital key and B is a constant, here you are moving the keys in a sort of floating pattern.

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.

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);
?>

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.