1

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;
}
1
  • bro, its not clear... Commented Sep 5, 2015 at 20:49

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for help i found it by myself, look at my solution above :)
0

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[])),
]

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.