foreach 循环内的自制函数?

发布于 2025-01-01 23:43:56 字数 207 浏览 2 评论 0原文

我有一个基于七层多维数组的大型函数?

当我像这样在 foreach 中调用函数时,

 foreach($items as $item) {
      makeItem($item, $items[$item]);
 }

它总是失败,为什么会这样,尽管如果我在 foreach 之外调用它们,它就可以了并且可以工作?

I have a large function that is based on a seven tier multidimensional array?

When I call the function in a for each like so

 foreach($items as $item) {
      makeItem($item, $items[$item]);
 }

It always fails why is this, although if I call them outside a foreach it is fine and works?

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

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

发布评论

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

评论(3

暖伴 2025-01-08 23:43:56

好的,现在您已经稍微更改了代码...问题是,当您像以前一样使用 foreach 循环时,循环变量不是数组的索引,而是数组中的元素。我仍然不清楚你的意图,但你可能想做类似的事情:

foreach($items as $key => $item) {
      makeItem($item, $items[$key]);
}

...这仍然没有意义,因为你会传入 $item 两次。

OK, now that you've changed the code a bit... The problem is that when you use a foreach loop as you did, the loop variable isn't the index of the array, it's the element in the array. Your intent is still unclear to me, but you might want to do something like:

foreach($items as $key => $item) {
      makeItem($item, $items[$key]);
}

...which still wouldn't make sense because you would be passing in $item twice.

琉璃繁缕 2025-01-08 23:43:56

很难从问题中看出,但如果您询问如何从 foreach 循环内部调用自己的函数并将一个项目传递给该函数,我相信您正在寻找的代码是:

foreach ($items as $item) {
        makeItem($item);
    }

< a href="http://php.net/manual/en/control-structs.foreach.php" rel="nofollow">http://php.net/manual/en/control-structs.foreach.php< /a>

Hard to tell from the question, but if you are asking how to call your own function from inside a foreach loop and pass an item to that function, I believe that the code you are looking for is:

foreach ($items as $item) {
        makeItem($item);
    }

http://php.net/manual/en/control-structures.foreach.php

痴情换悲伤 2025-01-08 23:43:56

为什么你在 foreach 中写了三次这个函数。每次只写一次就可以调用它。或者你能描述一下或发布一些更多的代码片段吗?

Why you have written the function three times in foreach.it can be called each time by writting it only once.or could you please describe or post some more code snipped .

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