I have a mysql table that looks like this:
id | id_transaction | id_item |
1 | it0001 | T0001 |
2 | it0001 | T0002 |
2 | it0001 | T0003 |
3 | it0002 | T0001 |
4 | it0002 | T0003 |
5 | it0003 | T0003 |
6 | it0003 | T0004 |
and I am trying to build a multi-dimensional array that would end up looking like this:
Array
(
array('T0001','T0002','T0003'),
array('T0001','T0003'),
array('T0003','T0004'),
);
I am using the select query:
$result = mysql_query("SELECT id_item,id_transaction from transaction_item ")or die("<br/><br/>".mysql_error());
Does anyone know how to do this?
1.Don't use mysql_*
it's deprecated+removed now. Use mysqli_*
OR PDO
for this
2.You din't did anything after query execution.
A mysqli_*
version code is:-
<?php
$dbhost = 'localhost'; //change credentails
$dbuser = 'root';//change credentails
$dbpass = '';//change credentails
$dbname = 'TUTORIALS';//change credentails
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
$sql = 'SELECT id_item,id_transaction from transaction_item';
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$final_array = array();
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$final_array[$row['id_transaction']][] = $row['id_item'];
}
echo "<pre/>";print_r(array_values($final_array));
} else {
echo "0 results";
}
mysqli_close($conn);
?>