简体   繁体   中英

Multidimensional SplFixedArray

This is the array :

Array
(
    [0] => Array
        (
            [ID] => 74
            [coupon] => fCHzP
        )

    [1] => Array
        (
            [ID] => 74
            [coupon] => WKHaY
        )
)

...etc

And this is the code that makes this array each time dynamically (by a given counter) and then save into db table:

for($i=0;$i < $this->counter;$i++){

  $query_params[ ] = array('ID' => $this->ID , 'coupon' => make_random());

}
self::insert($query_params);

Ι trying tο write a code that making a multi-dimensional array with SplFixedArray but i cant!

I already tried this code ( before loop ) but is not working:

$query_params = new SplFixedArray($this->counter);

Thanks !

The problem here is that $query_params[] = ...; doesn't work with SplFixedArray . When you do $query_params[] = ...; , you are adding an element after the last one.

With SplFixedArray count() always returns the "fixed" size, so when you push, you are trying to add an element outside of its range.

Try this:

$query_params = new SplFixedArray($this->counter);
for($i=0; $i < $this->counter; $i++){
  $query_params[$query_params->key()] = array('ID' => $this->ID , 'coupon' => make_random());
  $query_params->next();
}

Or, better yet:

$query_params = new SplFixedArray($this->counter);
for($i=0; $i < $this->counter; $i++){
  $query_params[$i] = array('ID' => $this->ID , 'coupon' => make_random());
}

The way you are creating the array is good, Laravel will accept it if your database server accept those lines, but looking at your code I see some strange things:

self::insert($query_params);

Tells me that this is an Eloquent model, or am I wrong?

$this->counter

This model has a counter on it, so this isn't a clean model...

array('ID' => $this->ID , 'coupon' => make_random());

You are trying to self::insert the ID again and again? Will that work for your table?

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