-1

Is it possible to do something like the following in PHO

I return an array from my DB that looks like the following

1, 2 ,3 now i want to add a forth number to it and then resort them so

1 becomes 5
2 becomes 1
3 becomes 2
Fourth Number becomes 3

or is there a away to rearrange my table so it rotates. What i am trying to do is rotate and return a row in the database in order but once it has been returned i want to my page i want to get a user to enter another row into my database and then put the row that had been returned to the end so it would have the highest value.

I am basically updating my column by subtracting one from all entries and increaseing my first entry to the highest number

a. 1,2,3
b. 4,1,2,3
c. 3,5,1,2,4
d. 2,4,6,1,3,5

Hmmmm I dont think what i am saying is exacty what i am looking for or maybe someone understands what i am trying to say so i wont change it.

Or if i could use a auto incremented key starting at 1 and just rearrange all the data in the other columns would work.

So do this 1. Count the number of row 2. Return an array with all database table entries 2. Add a new entry to the database on the last row. 3. Move the entry in 1 to the number of rows +1 (creating a new row 4. Move all other entries up one.

so here is is

1 -> a
2 -> b
3 -> c

after adding another row

1 -> b
2 -> c
3 -> d
4 -> a

After adding another row

1 -> c 
2 -> d 
3 -> a 
4 -> e
5 -> b 

After adding another row

1 -> d
2 -> a
3 -> e
4 -> b
5 -> f
5 -> c

After adding another row

1 -> a
2 -> e
3 -> b
4 -> f
5 -> c
5 -> g
5 -> d

WHO can come up with a solution for me?????

4

2 回答 2

0

尝试

$arr = array('a','b','c');
$value = 'd';
$arr = my_sort($arr, $value);
print_r($arr);
echo nl2br(PHP_EOL);
$arr = my_sort($arr, 'e');
print_r($arr);

function my_sort($arr, $value) {
  $arr[] = $value;
  $first = array_shift($arr);
  $arr[] = $first;

  return $arr;
}

检查http://codepad.viper-7.com/yJE8FR

于 2012-10-29T08:08:41.253 回答
0

您可以使用以下函数并将 shift 参数传递给它。函数名称为下面的 rotate_array()。使用该函数后添加下一个值。

<?php

$weekdays = array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun");

function rotate_array($steps, $arr)
{
    if($steps >= 0)
    {
        for($i = 0; $i < $steps; $i++)
        {
            $elm = array_shift($arr);
            array_push($arr, $elm);
        }
    }
    else
    {
        for($i = 0; $i > $steps; $i--)
        {
            $elm = array_pop($arr);
            array_unshift($arr, $elm);
        }
    }
    return $arr;
}

$arr = rotate_array(1, $weekdays);

//For multidimensional array, add this part

foreach($arr as $key => $childArray) {

       rotate_array(1,$childArray);


}
//end of addition

$arr[] = "next value";
echo "<pre>";
print_r($arr);
echo "</pre>";


?>

输出:

Array
(
    [0] => Tue
    [1] => Wed
    [2] => Thu
    [3] => Fri
    [4] => Sat
    [5] => Sun
    [6] => Mon
    [7] => next value
)
于 2012-10-29T08:10:14.390 回答