0

I'm trying to create an associative array in PHP using an Object. The Object is values from a database, called Category. It only has two values, an id and a name field.

This is what I have:

$category = $em->getRepository('AppBundle:Category')->findAll();

$stuff = array();

foreach($category as $cat) {
    $stuff[$cat->getName()] = $stuff[$cat->getId()];
}

But I get this nasty error:

Notice: Undefined offset: 1

I should say that I am using Symfony 3. Any help would be great.

LF00
  • 27,015
  • 29
  • 156
  • 295
Kaley36
  • 233
  • 9
  • 19

3 Answers3

0

You're on the right track but you need to remove echo since you're not trying to output anything. You're also attempting to assign a value from the array you're trying to enter a value into.

$stuff[ $cat->getName() ] = $cat->getId();
Nathan Dawson
  • 18,138
  • 3
  • 52
  • 58
0

Sorry I just omitted the value and replace with $cat->getId() in stead of $stuff[$cat->getId()] and it worked

Kaley36
  • 233
  • 9
  • 19
0

You $stuff array has no index 1, so it will cause that issue.

This is caused by $stuff[$cat->getId()];, which should be $cat->getId();

foreach($category as $cat) {
    $stuff[$cat->getName()] = $cat->getId();
}
LF00
  • 27,015
  • 29
  • 156
  • 295