I want to sort a multidimensional array, but I haven't used keys to create it. I used some columns from different tables in my database to store similar data into the array using for loops.
for($x = 0; $x < $numrows; $x++)
{
$Array[$x][0] = mysql_result($result,$x,"Date");
$Array[$x][1] = mysql_result($result,$x,"Ref");
$Array[$x][2] = mysql_result($result,$x,"Amount");
}
First Table is invoice details, the second is Payments made. I'm trying to print out a Statement. All works well, but not in date order. It prints out in the order that I input into the array: All invoice amounts, then all payment amounts. I make the Invoiced amount (-1 * $amount) to filter to Debit or Credit later on as below output.
I print using while loops as the amount of rows will keep growing.
A hard-coded Test Code:
/*#############################
# Sort Multidimentional Array #
#############################*/
//SET ARRAY
$Array [0][0] = "2016-01-01";
$Array [0][1] = "INV001";
$Array [0][2] = "-500.00";
$Array [1][0] = "2016-02-01";
$Array [1][1] = "INV002";
$Array [1][2] = "-550.00";
$Array [2][0] = "2016-01-05";
$Array [2][1] = "PAY001";
$Array [2][2] = "500.00";
$Array [3][0] = "2016-02-05";
$Array [3][1] = "PAY002";
$Array [3][2] = "500.00";
//SORT ARRAY
/* Need some help here */
//PRINT ARRAY
echo "<br/>Print out:<br/><br/>";
for ($x = 0; $x < 4; $x++ )
{
for ($y = 0; $y < 3; $y++ )
{
echo "Array [$x][$y]: ".$Array[$x][$y]."<br/>";
}
echo "<br/>";
}
echo "<br/>Done";
?>
I want to sort this in Date order so that after it has been sorted:
$Array [0][0] = "2016-01-01";
$Array [0][1] = "INV001";
$Array [0][2] = "-500.00";
$Array [1][0] = "2016-01-05";
$Array [1][1] = "PAY001";
$Array [1][2] = "500.00";
$Array [2][0] = "2016-02-01";
$Array [2][1] = "INV002";
$Array [2][2] = "-550.00";
$Array [3][0] = "2016-02-05";
$Array [3][1] = "PAY002";
$Array [3][2] = "500.00";
Current output:
+------------+--------+----------+----------+
| DATE | REF. | DEBIT | CREDIT |
+------------+--------+----------+----------+
| 2016-01-01 | INV001 | R 500.00 | |
+------------+--------+----------+----------+
| 2016-02-01 | INV002 | R 550.00 | |
+------------+--------+----------+----------+
| 2016-01-05 | PAY001 | | R 500.00 |
+------------+--------+----------+----------+
| 2016-02-05 | PAY002 | | R 500.00 |
+------------+--------+----------+----------+
| BALANCE DUE: R 50.00
Wanted output:
+------------+--------+----------+----------+
| DATE | REF. | DEBIT | CREDIT |
+------------+--------+----------+----------+
| 2016-01-01 | INV001 | R 500.00 | |
+------------+--------+----------+----------+
| 2016-01-05 | PAY001 | | R 500.00 |
+------------+--------+----------+----------+
| 2016-02-01 | INV002 | R 550.00 | |
+------------+--------+----------+----------+
| 2016-02-05 | PAY002 | | R 500.00 |
+------------+--------+----------+----------+
| BALANCE DUE: R 50.00