How to push an object into an array which is the value in a key/value pair in php

688 views Asked by At

I have chosen a Key => Value pair as my data structure where the Key is some text and the value is an array into which I will store objects. Here is where I declare my Key => Value (array)

$array = array(
  "key1" => array(),
  "key2" => array(),
  "key3" => array(),
);

I am trying to loop through and push a new object into the array, but I can't figure out how.

Something like:

While (...){
 ...
 $object = new obj();
 array_push($array['key1'], $object);
 ...
}

but with this I get the error

array_push() expects parameter 1 to be array
1

There are 1 answers

2
Rasclatt On

Can't you just do this:

for($i=1; $i < 20; $i++) {
    $array['key'.$i] = (object) array();
}

Does the object need any kind of properties??

EDIT:

Try this modification:

While (...){
 ...
 $object = new obj();
 $array['key1'] = $object;
 ...
}

Another possiblity??

While (...){
 ...
 $object = new obj();
 $array['key1'][] = $object;
 ...
}