1

I have this table:

Username,     Fan,        Count
1danny22,     katana1973, 2
bob,          rita,       2
mattyhacky,   hayley,     2
mattyhacky,   dickie1eye, 1
mattyhacky,   xxjodiexx,  1

And I want to load it into an associative array which would looks like this:

Array ( 
    [1danny22] => Array (
        [katana1973] => 2,
    ),
    [bob] => Array (
        [rita] => 2, 
    ),
    [mattyhacky] => Array (
        [hayley] => 2,
        [dickie1eye] => 1,
        [xxjodiexx] = > 1,
    )
)
$strSQL = "SELECT username, fan, count( * ) AS intCount
FROM fan
GROUP BY username, fan              
ORDER BY username, intCount DESC";

$strResult = mysql_query($strSQL);
while($objRow=mysql_fetch_object($strResult))
{
  code should go in here!!!
}

But I'm really struggling.

Can someone please help?

Many thanks

TheBounder.

1
  • Struggling with what? What have you tried so far? Commented Jul 12, 2011 at 19:51

3 Answers 3

4

Easy peasy...

$sql = "SELECT Username, Fan, Count FROM datatbl";
$res = mysql_query($sql);

while ($row = mysql_fetch_object($res))
  $data[$row->Username][$row->Fan] = $row->Count;

I should explain further. What your doing here is creating a base index for your data array that uses the common associate Username as the index. Within that index you have another array, this using the Fan as the index and the value of each item being the count. My above example is the easiest way to build the structure that you are looking at.

Now if you run a print_r on the array you will see the structure you defined.

Sign up to request clarification or add additional context in comments.

Comments

2

assuming your initial array is in $data, with for instance

$data[0] = array("1danny22", "katana1973", 2);

you could go with

$output = array();
foreach($data as $line) {
    $output[$line[0]][$line[1]] = $line[2];
}

Comments

0

You could build it programmatically from the returned result... bare bones example:

$ar = array();
$result = mysql_query("SELECT * FROM your_table");
while ($ar[] = mysql_fetch_assoc($result));


print_r($ar);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.