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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.