Jump to content

Help Arrays!!!


myITguys

Recommended Posts

I have a set of data in 4 arrays

 

Name() Stock() UserID() Price()

 

I can pull the data out of the arrays in a for loop and they are related by a variable $i

for ($i=0; $i<count($Name);$i++)

{

echo $Name[$i] . ' - ' . $Stock[$i] . ' - ' . UserID[$i] . ' - ' . Price[$i];

}

 

This works fine

Yahoo - 1000 - 2 - $1.25

Blue - 10000 - 3 - $2.25

Pink - 3000 - 2 - $1.67

Yahoo - 4000 - 5 - $5.00

 

However If the Name is the same (repeated) i don't want this printed out twice

i need the above to look like

 

Yahoo - 1000 - 2 - $1.25

        - 4000 - 5 - $5.00

Blue    - 10000 - 3 - $2.25

Pink    - 3000 - 2 - $1.67

 

I cant figure out an easy way to do this, by combining arrays, removing duplicates..

 

Please help... I'm lost at the moment. Thanks :)

 

 

 

 

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

you modify this code

for ($i=0; $i<count($Name);$i++)
{
echo $Name[$i] . ' - ' . $Stock[$i] . ' - ' . UserID[$i] . ' - ' . Price[$i];
}

to following

for ($i=0; $i<count($Name);$i++)
{
echo $Name[$i]
for ($j=0; $j<count($Stock);$j++)
{
echo $Stock[$j] . ' - ' . UserID[$j] . ' - ' . Price[$j];
}

Link to comment
https://forums.phpfreaks.com/topic/71780-help-arrays/#findComment-361481
Share on other sites

I'd keep the items together in a single array. Sort them by name in the query.

 

<?php
$sql = "SELECT name, stock, userid, price FROM table ORDER BY name" ;
$res = mysql_query($sql);
while ($row = mysql_fetch_assoc($res))
{
    $data[] = $row;
}

$prevname='';
foreach ($data as $item)
{
    $itemname = $item['name'] == $prevname ? '' : $item['name'] ;
    $prevname = $item['name'];
    
    echo $itemname, ' - ', $item['stock'], ' - ', $item['userid'], ' - ', $item['price'], '<br />';
}
?>

Link to comment
https://forums.phpfreaks.com/topic/71780-help-arrays/#findComment-361592
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.