PHP数组切片多个数组不起作用

发布于 2024-11-24 06:18:35 字数 682 浏览 1 评论 0原文

以下将 $scpar 分为两种类型,一种包含前 9 个,第二种包含从 10 到 18 的前逗号分隔值。

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

然后,我们使用 foreach 并使用 id 参数 $sid 来获取相同的逗号将值与其他字段分开。

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

然后像这样从其他领域获取信息。

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

一切正常,问题出在第二个 9 个字段上。

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

字段 $scpar 是正确的,但包含 [$sid] 的字段是从第一个结果开始,而不是从第 9 个结果开始。

有什么想法吗?

奇妙

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

a√萤火虫的光℡ 2024-12-01 06:18:35

您需要使用 preserve_keys

保留密钥:
请注意,array_slice() 将重新排序并重置数组索引
默认情况下。您可以通过将preserve_keys设置为来更改此行为
正确。

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

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);
尝蛊 2024-12-01 06:18:35

如果要保留键($sid),则需要将 array_slice 的第四个参数设置为 true,请参阅 http://php.net/manual/en/function.array-slice.php

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

瘫痪情歌 2024-12-01 06:18:35

array_slice() 创建包含的新数组来自原始数组,而不是键。在原始数组的上下文中使用 foreach 循环中的键是没有意义的,因为这些是新切片数组中的键。

使用 array_slice($scpar, 9, 18, true) 也可以复制键,而不仅仅是值:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文