Mico
Mico

Reputation: 497

Generate multi-dimensional array from retrieved rows

I have this data retrieved from a MySQL database:

enter image description here

And now I want to create the following array from the retrieved rows above...

enter image description here

Any ideas how to do that? TIA!

Upvotes: 0

Views: 102

Answers (5)

asarfraz
asarfraz

Reputation: 518

Well you try this and this should work

 $rs = mysql_query('SELECT * FROM tbl order by product_code asc');

 $arr = array();
 $num = 0;
 $strTemp = '';

 while($data = mysql_fetch_object($rs)) {
      if ($strTemp !=  $data->product_code) {
           $strTemp =  $data->product_code; 
           $num = 0;
      }
      $arr[$strTemp][$num] = $data->unit_of_measure;
      $num++;
 }

Upvotes: 0

Mandip Darji
Mandip Darji

Reputation: 775

$result = mysql_query("select * from stack");
$my_array = array();
// Run Query here to get $result

while ($obj = mysql_fetch_array($result)) {

    $my_array[$obj['product_code']][] = $obj['unit'];

}

echo "<pre>";
print_r($my_array);
echo "</pre>";
exit;

OUTPUT

Array
(
    [1111] => Array
        (
            [0] => piece
            [1] => case
        )

    [2222] => Array
        (
            [0] => piece
        )

    [3333] => Array
        (
            [0] => piece
        )

    [8888] => Array
        (
            [0] => box
            [1] => pack
            [2] => piece
        )

)

Upvotes: 0

Lajos Arpad
Lajos Arpad

Reputation: 76444

Run this query:

select productcode, group_concat(unitofmeasure separator ",") from product group by productcode

and then, when you iterate the results in PHP, use the explode function.

Upvotes: 0

Aaron Gong
Aaron Gong

Reputation: 1005

Use object results, and use mysqli (or anything else buy mysql)

$my_array = array();

// Run Query here to get $result

while ($obj = mysqli_fetch_object($result)) {

    $my_array[$obj->Product_Code][] = $obj->Unit_Of_Measure;

}

Upvotes: 0

invisal
invisal

Reputation: 11171

Well, the simplest way is to manually group data in PHP code for example:

$stm = $db->query('SELECT * FROM tbl;');
$result = array();
while($row = $stm->fetch()) {
    $result[$row['productcode']][] = $row['unit'];
}

var_dump($result);

Upvotes: 2

Related Questions