开发者

PHP array slice multiple array non functional

The following slices $scpar into two types one containing the first 9 and the second containing former comma separated values from 10 to 18.

$scpar9 = array_slice($scpar,0,9);
      $scpar18 = array_slice($scpar,9,18);

We then use a foreach and use an id parameter $sid to get the same comma separated value from other fields.

foreach ($scpar9 as $sid => $scpar) {

Information is then taken from other fields like this.

<b>'.$scpar.'</b> '.$sccomp[$sid].$scmen[$sid].

That all works fine, the problem is with the second 9 fields.

foreach ($scpar18 as $sid => $scpar) {
<b>'.$scpar.'</b> '.$sccomp[$sid].$scmen[$sid].

The field $scpar is correct but the ones containing the [$sid] are starting from the first result not the 9th.

Any ideas?

Marvellous开发者_开发知识库


you need to use preserve_keys

preserve_keys : Note that array_slice() will reorder and reset the array indices by default. You can change this behaviour by setting preserve_keys to TRUE.

   $scpar18 = array_slice($scpar,9,18, true);


If you want to preserve the keys ($sid), you need to set the fourth param to true for array_slice, see http://php.net/manual/en/function.array-slice.php


array_slice() creates new arrays containing the values from the original arrays, not the keys. Using the keys in the foreach loop is meaningless in the context of the original array, since these are the keys from the new slice arrays.

Use array_slice($scpar, 9, 18, true) to copy the keys as well, not just the values:

$scpar18 = array_slice($scpar, 9, 18, true);
                                  #    ^^^ preserve keys
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜