简体   繁体   English

如何从插入的SQL排序二维数组PHP

[英]how to sort 2d array php from sql inserted

This is my inseted sql to array 这是我插入的SQL数组

$e=0;
while ($row45 = mysqli_fetch_array($res1)) {
                $proIdArr0["id"][$e]=$row45['proId'];
                $proIdArr0["qty"][$e]=$row45["proQty"];
                $e++;
            }
print_r($proIdArr0);

And it prints 它打印

Array ( 
[id] => Array ( 
    [0] => 15
    [1] => 13
    [2] => 16 ) 

[qty] => Array ( 
    [0] => 54
    [1] => 84
    [2] => 54 ) 
)

and i want to sorted by the id so it will be for example this output 而且我想按ID排序,因此将例如此输出

id | qty
-------
13 | 84
15 | 54
16 | 54

You can combine your array and then ksort it. 您可以合并数组,然后对其进行ksort

<?php

$array = [
 "id" => [15,13,16],
 "qty" => [54,84,54]
];

$combined = array_combine($array['id'], $array['qty']);
ksort($combined);
var_dump($combined);

Returns: 返回值:

array(3) {
  [13]=>
  int(84)
  [15]=>
  int(54)
  [16]=>
  int(54)
}

Make id as the key and qty as value to sort on id , then some reverse enginering to get desired result. 将id作为键,将qty作为值对id进行排序,然后进行一些反向工程以获得所需的结果。

<?php
$com = array_combine($proIdArr0["id"], $proIdArr0["qty"]);
ksort($com);
foreach($com as $k=>$v)
{
$proIdArr0["id"]=$k;
$proIdArr0["qty"]=$v;
}

But using order by in query is more preferable solution. 但是在查询中使用order by是更可取的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM