PHP array building help please

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jucedupp
Forum Newbie
Posts: 1
Joined: Mon May 24, 2010 4:14 am

PHP array building help please

Post by jucedupp »

Hi there guys,

I would truly appreciate any help you could give me on this:

PHP/MySql

I have a form that posts an array back to itself:

The post array looks like this:

Array ( [0] => 1 [1] => 2)

I then loop through the array as $type:

The query:

SELECT i.name, d.price, d.date FROM data d INNER JOIN items i ON (d.item_id = i.id) WHERE i.id = '.$type.' ORDER BY i.name

For each of the array I get this:

peanuts, 1000, 20100401
peanuts, 1100, 20100402
tomatoes, 400, 20100401
tomatoes, 401, 20100402

etc

What I need in the end is an array that looks like this:

Array ( [Peanuts] => Array ( [20100401] => 1000 [20100402] => 1100 ) [Tomatoes] => Array ( [20100401] => 400 [20100402] => 401 ) )

Can anyone help me to construct the query/loop that will achieve this?
If you could just use the above data, it would be perfect.

Any help would be sincerely appreciated and the person(s) who help with this will get an honorable mention and link in the source.

Cheers

Jacques
User avatar
markusn00b
Forum Contributor
Posts: 298
Joined: Sat Oct 20, 2007 2:16 pm
Location: York, England

Re: PHP array building help please

Post by markusn00b »

Something like this?

Code: Select all

<?php

function restructureArray($array) {
    $new_array = array();
    
    foreach ($array as $inner_array) {
        $new_array[$inner_array[0]][$inner_array[2]] = $inner_array[1];
    }
    
    return $new_array;
}

$array = array(
    array('peanuts', 1000, 20100401),
    array('peanuts', 1100, 20100402),
    array('tomatoes', 400, 20100401),
    array('tomatoes', 401, 20100402)
);

print_r(restructureArray($array));
The code is pretty easy-to-understand, though if you want me to elaborate I will. :)
Post Reply