user3759502
user3759502

Reputation: 21

PHP Store multiple values in key

Is it possible to store multiple values in one key?

I loop through all items in my db which have the following propertys:

category, itemname and itemurl

now i want to sort all items by category, which means some items have the same category and i want them to be together in my object which should look like this:

Items [
    category1 => item1[], item2[], item3[]
    category2 => item4[], item5[]
    category3 => item6[]
]

Thanks for your help!

Solution: You can store the values in an anonymous array

while ( $stmt->fetch()  ) {

    $tempArray = [
        'xxx' => xxx,
        'yyy' => yyy,
        'zzz' => zzz
    ];
    Items[category][ ] = $tempArray;
}

Upvotes: 1

Views: 2322

Answers (2)

CollinD
CollinD

Reputation: 7573

I may not be understanding the question properly, but storing multiple values per key is very easy in php

$items[0]['category'] = "Category 1"
$items[0]['itemname'] = "Item Numero Uno"
$items[0]['itemrul'] = "myfavoriteitem.com"

$items[1]['category'] = // . . . you get it

To reorganize them by category, should be fairly easy

$categorized = array();

foreach ($items as $item) {
    $categorized[$item['category']][] = $item; //append item to the category
}

Upvotes: 1

q.Then
q.Then

Reputation: 2753

I'm not sure if I fully understand you, but if I'm correct with what you're trying to achieve:

Just use an array to store them (you can't have a one key to many objects, but you can have a one key to one object and that one object can store many other objects)

Items [
    category1 => array(item1[], item2[], item3[]),
    category2 => array(item4[], item5[]),
    category3 => array(item6[])),
]

Upvotes: 0

Related Questions