[英]PHP Multi Dimensional Array Sorting
Here is my Table Structure, 这是我的表结构,
I want to display as 我想显示为
I mean, the second coloumn (name) should be in Ascending Order and the third coloumn (place) should be in Descending Order. 我的意思是,第二列(名称)应按升序排列,而第三列(位置)应按降序排列。
How i want is 我想要的是
The Name should be in Asc Order and then to the right, the Place should be in Desc Order 名称应按升序排列,然后在右侧,位置应按降序排列
What i have tried so far is 到目前为止,我尝试过的是
How can i do this ?? 我怎样才能做到这一点 ??
<?php
include ('conn.php');
$sql="SELECT * FROM test";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
while($rows=mysql_fetch_array($result))
{
foreach($result as $k=>$v)
{
echo $k;
}
}
?>
It displays the result as Invalid argument supplied to for each. 它将结果显示为为每个提供的Invalid参数。 What is the mistake i am doing and how can achieve my output
我正在做的错误是什么,如何实现我的输出
To fix the sorting, just add ORDER BY name, place 要解决排序问题,只需添加ORDER BY名称,位置
Then there's several more issues preventing this from working: 然后还有其他一些问题使它无法正常工作:
$rows
, not $result
(this is where the "invalid argument" error is coming from). $rows
而不是$result
(这是“无效参数”错误的出处)。 You might want to do something like this to fix these: 您可能需要执行以下操作来解决这些问题:
<?php
include('conn.php');
$sql = "SELECT * FROM test ORDER BY name, place";
$result = mysql_query($sql);
while ($rows = mysql_fetch_array($result)) {
foreach ($rows as $k => $v) {
echo "$k is $v. ";
}
echo "<br/>";
}
?>
那么,为什么不像这样在查询中进行订单
SELECT * FROM test order by name;
You can do this only modifying query. 您只能执行修改查询的操作。
Use this query: 使用此查询:
SELECT * FROM test ORDER BY name ASC, place DESC
For your error, you are using wrong variable as foreach. 对于您的错误,您使用了错误的变量作为foreach。 Replace this -
取代这个-
foreach($result as $k=>$v)
{
echo $k;
}
with this - 有了这个 -
foreach($rows as $k=>$v)
{
echo $k;
}
Buy why are using foreach inside while loop. 购买为什么在while循环中使用foreach。 You can get your values like -
您可以得到像-
while($rows = mysql_fetch_array($result)) {
echo $rows['name'].' '.$rows['place'].'<br/>';
}
and don't use mysql_*
function. 并且不要使用
mysql_*
函数。 Use instead mysqli_*
改用
mysqli_*
And for your expected output, try using following query - 为了获得预期的输出,请尝试使用以下查询-
SELECT * FROM `test` order by name asc, place desc
This is the kind of thing you can fix using array_multisort. 您可以使用array_multisort修复这种问题。 Try the below example (which I have not tested yet, but ought to work)
请尝试以下示例(我尚未测试过,但应该可以使用)
<?php
include ('conn.php');
$sql="SELECT * FROM test";
$result=mysql_query($sql);
$totals = array();
$row = array();
$places = array();
while($row=mysql_fetch_array($result)){
$totals[] = $row
$names[] = $row['name'];
$places[] = $row['place'];
}
array_multisort( $names, SORT_ASC, $places, SORT_DESC, $totals );
// now you can use $totals, which is sorted as you want
print_r( $totals );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.