【问题标题】:how to sort an array in descending order in php如何在php中按降序对数组进行排序
【发布时间】:2020-05-16 01:04:48
【问题描述】:

新输入的产品显示在最后一行。如果量大,底部很难看到。如何将新显示更改为顶部。谢谢!

$barcodes_ary = explode(',', $barcodes);
    $barcodes_hash = array ();
    foreach ($barcodes_ary as $b) {
        if (array_key_exists($b, $barcodes_hash)) {
            $barcodes_hash[$b] += 1;
        } else {
            $barcodes_hash[$b] = 1;
        }
    }
    foreach ($barcodes_hash as $b => $amount) {
        if ($barcodes_ary == array(''))continue; 
        $ary = get_sql("SELECT * FROM Products WHERE Barcode='$b' Order by ProductName");
                    if ( count($ary) == 0 ) {
            continue;
        } 
        $pid  = $ary[0]['ProductID'];
        $pn   = $ary[0]['ProductName'];
        $unit = $ary[0]['UnitID'];

        $ary2 = get_sql("SELECT UnitName FROM Units WHERE UnitID = '$unit'");
        $unit = $ary2[0]['UnitName'];

        ?>
        <TR>
        <TD><? echo "$pn"; ?></TD>
        <TD>
        <INPUT TYPE=hidden NAME=productid<?=$pid?>        VALUE='<?=$pid?>'>    
        <?
        $candidates = array();
        for($i=1; $i <= DropDownMaxValue; $i++) {
            $candidates[]=$i;
        }

//更新 我用另一种方法来解决问题。只需展示相同的产品即可。

function push_barcode() {
// alert('barcode pushing');
b  = document.form1.barcode;
bs = document.form1.barcodes;
if (bs.value == "") {
    bs.value = b.value;
} else { // ?? 111,333,444,... ???
    bs.value = b.value;
}

}

【问题讨论】:

  • 为什么不直接反转数组?
  • "SELECT * FROM Products WHERE Barcode='$b' Order by ProductName DESC" DESC 将从末尾开始并向后排序查询...
  • @Premlatha krsort($ary);不工作
  • @dalelandry $ary = get_sql("SELECT * FROM Products WHERE Barcode='$b' Order by ProductName DESC");不工作。

标签: php arrays sorting sql-order-by


【解决方案1】:

好的,您应该能够使用数组的括号中反向返回的keys 值来获取计数。

尝试以下方法,看看它是否适合您......

$ProductName = $ary[0]['ProductName'];
//--> get the count of your array
$count = count($ProductName);
//--> define an output variable to hold values
$output = null;
$i = 0;
//--> reduce count by one as key values start at 0 and count starts at 1
$count = $count - 1;
//--> subtraction and addition of $count by one to reduce warning 
//--> of `undefined offset` for index on mismatched key values
while($count + 1){
        //--> concatenate the values into a variable for display
        $output .= $ProductName[$count];
        //--> or push the reversed values back into an array 
        $product_name[$i] = $ProductName[$count];
        //--> $product_name should now hold your values in reverse use a foreach 
        // use a foreach to display values in your table
        $count--;
        $i++;
}

【讨论】:

  • 谢谢。您的意思是在此处添加? $ary = get_sql("SELECT * FROM Products WHERE Barcode='$b' Order by ProductName"); //你在这里编码? if ( count($ary) == 0 ) { 继续; }
  • 基本上,您通过声明一个新数组并使用在运行循环时递减的计数来反转键值来重构数组并将值推回。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-16
  • 2011-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-20
相关资源
最近更新 更多