简体   繁体   中英

How to create multi-dimensional associative array

I have this example table data, it actually has ids, prices, more stuff, but i think i can ask with this data, im using PHP as my language:

id   category  product       complement_type   option
 1   Pizza     Large Pizza   Bread             Brown bread
 2   Pizza     Small Pizza   Bread             White bread
 3   Pizza     Small Pizza   Ingredients       Olives
 4   Salads    Green Salad   Extras            Bacon
 5   Salads    Cesars Salad  Extras            Lettuce

i already have the query for this table,

now i want to convert ir to an array of this type

array(
 [Pizza] => array(
             [Large Pizza] => array(
                                [Bread] => Brown Bread
                              )
            ),
            array(
             [Small Pizza] => array(
                                [Bread]        => White Bread
                                [Ingredients]  => Olives
                              ),
            )
 ),
 [Salads] => array(
             [Green Salad] => array(
                               [Extras]         => Bacon
                              )
             [Cesar Salad] => array(
                               [Extras]         => Lettuce
                              )
 )

that array is what i am trying to achieve, but i just cant get it right

i know i have to loop it with a for loop, maybe add a while loop to get the changes in the categories, but i just dont seem to find the way to do it, any ideas on how to achieve this?

i appreciate any idea

Again, im using PHP

thanks

Edit: heres the link to the data im getting, its a little different, but its the same principle

https://dobleslash.com/TakeEatEasy/API/getRest?id=1

First of all: your original array — as posted is comment — if an array of objects: this preliminar note is to understand the syntax -> , otherwise obscure simply reading your main question.

Assuming your table results are stored in array $array , you can try in this way:

$result = array();
foreach( $array as $row )
{
    if( !isset( $result[ $row->category ] ) ) 
    {
        $result[ $row->category ] = array();
    }
    if( !isset( $result[ $row->category ][ $row->product ] ) )
    {
        $result[ $row->category ][ $row->product ] = array();
    }
    $result[ $row->category ][ $row->product ][ $row->complement_type ] = $row->option;
}

At beginning, I init an empty array. Then — through a foreach loop, I process each element of $array and — if primary key (the product) doesn't exist in the result array, I create it as empty array; then I perform same action for category subkey (Large Pizza, etc). At last, I add the complement type.

eval.in demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM