Jump to content

Array Help


stig1

Recommended Posts

I have a database design that was given to me, to which I can not change the way it is designed.

 

The structure is the following format, if you ran just a normal select statement.

 

Item

QTY

9999

1

9999

10

9999

100

9888

10

9888

100

7777

100

 

There is plenty more data in the table, however, this is just example data.

 

What I want to achieve is to put this data into an array in the following format, item code, qty1, qty2, qty3, etc. Is this possible? New array key for each different item code.

 

So the data will look like the following:

 

9999 1 10 100

9888 10 100

7777 100

 

How would I do achieve this outcome?

Link to comment
https://forums.phpfreaks.com/topic/207462-array-help/
Share on other sites

Fairly simply:

$array = array();
while($row = mysql_fetch_assoc($query)){
   $array[$row['item_code']][] = $row['item_qty'];
}

print_r($array);

 

That will give output like:

 

Array
(
    [999] => Array
        (
            [0] => 4
            [1] => 5
        )

    [888] => Array
        (
            [0] => 3
        )

)

Link to comment
https://forums.phpfreaks.com/topic/207462-array-help/#findComment-1084664
Share on other sites

Here is another way to display the results, makes it a little easier:

 

$array = array();
$found = false;

while($row = mysql_fetch_assoc($query)){
    foreach($array as $key => $val){
        if($val['code'] == $row['code']){
            $found = true;
            break;
        }else{
            $found = false;
        }
    }

    if($found === false){
        $array[$row['code']] = array(
            'code' => $row['code'],
            'qty1' => $row['qty']
        );
    }else{
        $array[$row['code']]['qty' . count($array[$row['code']])] = $row['qty'];
    }
}

 

That will give you a resulting array like:

 

Array
(
    [999] => Array
        (
            [code] => 999
            [qty1] => 4
            [qty2] => 5
        )

    [888] => Array
        (
            [code] => 888
            [qty1] => 3
        )

)

 

That way you can access them like so:

 

echo $array['999']['qty1'];

Link to comment
https://forums.phpfreaks.com/topic/207462-array-help/#findComment-1084701
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.