2010-05-31 65 views
1

可能对你们来说很容易。我正在尝试对表单发送的$ _POST变量进行排序,并在mysql中更新排序后的结果。我不知道该怎么做,并感谢任何人都可以帮助我。

我main.php

//I have a loop here. (omitted) 
//$k will be increased by 1 every time the loop starts, so I will know the total times of the loops 
//the form will be submitted to update.php 


echo "<input type='hidden' name='pickTotal' value='".$k."' />"; 
echo "<input type='hidden' id='point' name='earnedPoint".$k."' value='".$point."' />"; 
echo "<input type='hidden' id='users' name='userName".$k."' value='".$userPick['user']."' />"; 

//loop ends 

我update.php

if(isset($_POST['submit'])){ 

    $pickTotal=$_POST['pickTotal']; //get the total loop 

    for ($p=0;$p<=$pickTotal;$p++){ 

     $userToBeUpdated=$_POST['userName'.$p]; 
    $userPoint=$_POST['earnedPoint'.$p]; 

     //sort the $userPoint here. 
     //I need to find out who got the most points 
     //and list user's place. 1st, 2nd, 3rd...etc. 


     //update my mysql 
    } 

感谢您的任何帮助。

回答

3

相反计数$ k和$ P的,你应该使用PHP的特殊形式的名称语法:

<input name="earnedPoint[]" value="..."> 
<input name="userName[]" value="..."> 

您收到这两个参数列表已经这样,$ _ POST [ “earnedPoint”] [0]直到$ _POST [“earnPoint”] [99]对应于$ _POST [“userName”] [0] .. [99]。

然后,只需映射两个数组:

$sort_us = array_combine($keys=$_POST["userName"], $values=$_POST["eP"]); 
arsort($sort_us); 

这应该让你的最高优先。

+0

谢谢。 PHP特殊的表单名称语法非常有用。 – FlyingCat 2010-05-31 00:31:13

+0

我会给你接受的答案,因为你是第一个调出php名称语法的人。 :D – FlyingCat 2010-05-31 00:40:36

1

你必须有一个标准来排序。

无论如何,sort函数应该可以帮到你。

+0

谢谢你的提示。 +1 – FlyingCat 2010-05-31 00:18:18

4

我建议非常相似,马里奥建议的东西,但在一个稍微不同的方式:

echo "<input type='hidden' id='point' name='user[$k][points]' value='".$point."' />"; 
echo "<input type='hidden' id='users' name='user[$k][name]' value='".$userPick['user']."' />"; 

当你拿到$_POST回来,你就会有一个这样的数组:

$_POST['user'] = array(
    0 => array(
     points => 15, 
     name => joe 
    ), 
    1 => array(
     points => 21, 
     name => john 
    ) 
); 

从那里,你可以使用usort拿出一个自定义的排序函数:

$data = $_POST['user']; 
usort($data, 'usortPost'); 

function usortPost($a, $b) { 
    if ($a['points'] == $b['points']) return 0; 
    return $a['points'] < $b['points'] ? 1 : -1; 
} 
+0

不错。 +1。肯定会更多地指出问题,然后我的答案。 – vladv 2010-05-31 00:33:29

+0

不错的使用php php名称语法。不知道它可以这样玩。 +1 – FlyingCat 2010-05-31 00:38:33

1

你可以,如前面提到的,使用由PHP提供的语法糖:

echo "<input type='hidden' id='point' name='earnedPoint[{$userPick['user']}]' value='".$point."' />"; 

你可以在这样的后端处理这个问题:

foreach ($_POST['earnedPoint'] as $user => $points) { 
    // update your SQL table 
} 

asort($_POST['earnedPoint']); // sort array in ascending order, maintain index assoc 

// save your data somehow 
+0

不错的一个!感谢您使用php的语法。 +1。 – FlyingCat 2010-05-31 00:39:31