array_diff &重新编号数字键

发布于 2024-08-23 09:03:52 字数 291 浏览 3 评论 0原文

(I'm a beginner)

我的脚本相当广泛地使用了该标准

$c = 0;
$t = count($array);

while ($c < $t) {
  $blah = $array[$c];
  ++$c;
}

。但我刚刚遇到了一种情况,我还需要 array_diff ,它打破了这一切,因为现在数字键有间隙。我到处都收到未定义的偏移量错误。

如何重置数组的数字键?数组中对象的顺序无关。

(I'm a beginner)

My script uses the standard

$c = 0;
$t = count($array);

while ($c < $t) {
  $blah = $array[$c];
  ++$c;
}

rather extensively. But I just ran into a situation where I also need array_diff and it breaks that all to hell because now the numeric keys have gaps. I'm getting Undefined offset errors all over the place.

How do I reset the numeric keys of an array? The order of the objects in the array is irrelevant.

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

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

发布评论

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

评论(3

娇柔作态 2024-08-30 09:03:52

要重置键,您可以使用 array_values()

$array = array_values($array);

To reset the keys, you can use array_values():

$array = array_values($array);
苍景流年 2024-08-30 09:03:52

您不需要重置数组的键:您必须改变您处理数组的方式。

您应该使用 foreach 循环,而不是使用 while 循环并通过索引访问数组元素,它只会从数组中获取元素:

foreach ($array as $key => $value) {
    // $key contains the index of the current element
    // $value contains the value of the current element
}

You don't need to reset the keys of you array : you have to change the way you are going through it.

Instead of using a while loop and accessing the array elemnts by index, you should use a foreach loop, which will only get you elements from the array :

foreach ($array as $key => $value) {
    // $key contains the index of the current element
    // $value contains the value of the current element
}
我喜欢麦丽素 2024-08-30 09:03:52

谢谢塔图。

对于lulz,我将与您分享我在等待明智答案时使用的以下白痴黑客:

$badArray = array_diff($allData, $myData);

$string = implode(",",$badArray);

$dump = explode(",",$string);

$goodArray = $dump;

有效。让我感觉很脏,但它有效。

Thank you Tatu.

For the lulz, I will share with you the following idiot hack I used while waiting for a sensible answer:

$badArray = array_diff($allData, $myData);

$string = implode(",",$badArray);

$dump = explode(",",$string);

$goodArray = $dump;

worked. Made me feel all dirty, but it worked.

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