Jump to content
tobeyt23

Array Layout Help

Recommended Posts

Ok I am having a brain fart and/or not enough coffee! See the below array:

Array
(
    [0] => Array
        (
            [breed_name] => Boxer
            [dog_name] => Fred
        )

    [1] => Array
        (
            [breed_name] => Labrador Retriever
            [dog_name] => Roxy
        )

    [2] => Array
        (
            [breed_name] => Labrador Retriever
            [dog_name] => Semper
        )

    [3] => Array
        (
            [breed_name] => Mixed Breed
            [dog_name] => Bronchito
        )

    [4] => Array
        (
            [breed_name] => Mixed Breed
            [dog_name] => Fonz
        )

    [5] => Array
        (
            [breed_name] => Mixed Breed
            [dog_name] => Triton
        )

)

I need to lay this out like so:

 

Boxer - Fred 
Labrador Retriever - Roxy, Semper 
Mixed Breed - Bronchito, Fonz, Triton

 

Any help would be appreciated as i am just banging my head currently!

Share this post


Link to post
Share on other sites

If you stored this into a dbms table you could write a query to organize the data in any fashion you might need today and in the future. If this is meant to be any kind of static data, I highly recommend that you re-think your storage plan. Sure you can do this, but the better approach is as I am suggesting.

Share this post


Link to post
Share on other sites

Would have been nice if you mentioned that.

 

Do your query to order the results by breed. Then loop thru the results echo'ing the breed and name on the first record. Then on the following records echo the name until you see a change in breed at which time you begin a new row with the breed name and the new dog name. And repeat. You'll have to save the 'last-breed' name after each record and use it to compare against the next record every time.

 

A very common approach to your problem.

Share this post


Link to post
Share on other sites

Feeling magnanimous today:

$q = 'select breed_name, dog_name from dogs_table
order by breed_name';
$qrslts = $pdo->query($q);
if (!$qrslts)
{
echo "Could not execute query";
exit();
}
$last_breed = 'xxx';
while(list($breed, $name) = $qrslts->fetch(PDO::FETCH_NUM))
{
if ($breed <> $last_breed)
{
if ($last_breed <> 'xxx')
echo '<br>';
echo "$breed - $name";
}
else
echo ", $name";
$last_breed = $breed;
}

 

 

(too bad the forum doesn't recognize the tabs in this code.)

Edited by ginerjm

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×

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.