简体   繁体   English

$ _GET中的foreach循环添加了奇怪的值

[英]foreach loop from $_GET is adding strange values

I have the following piece of code that is supposed to create a coma separated string from a URL returned when somebody installs a Facebook Tab: 我有以下代码,应该从有人安装Facebook标签时返回的URL创建以逗号分隔的字符串:

$tabs_added = $_GET['tabs_added'];
$tabs_added_array = array();
foreach($tabs_added as $key => $value){
    $tabs_added_array[] = $key;
}
$the_tabs = implode(',', $tabs_added_array);

The page is called and returned by Facebook like this: 该页面由Facebook调用并返回,如下所示:

tabs.php?tabs_added[1202358366491085]=1&tabs_added[144695175064017]=1
&tabs_added[676066073448810]=1#_=_

For some strange reason, the string it generates however is: 由于某些奇怪的原因,它生成的字符串是:

1202358366491085,144695175064017,676066073448810,0,1,2

As you can see, the beginning is correct, but then it adds 0,1,2 for no reason. 如您所见,开始是正确的,但随后无缘无故地将0,1,2相加。 Why is that and how can I avoid this? 为什么会这样,我该如何避免呢?

Your array looks like this: 您的数组如下所示:

[0]=>[1202358366491085]
[1]=>[144695175064017]
[2]=>[676066073448810]

Try it out with: var_dump($tabs_added_array); 尝试使用: var_dump($tabs_added_array); after the foreach. 在foreach之后。

And the string gets both. 字符串同时获得。 The code you show is not producing the indexes of the array though. 您显示的代码虽然不会产生数组的索引。

I've tested this myself and this is the URL I have: 我已经对此进行了测试,这是我拥有的URL:

test.php?
tabs_added[1202358366491085]=1&tabs_added[144695175064017]=1
&tabs_added[676066073448810]=1#_=_

And my code: 而我的代码:

$tabs_added = $_GET['tabs_added'];
$tabs_added_array = array();
foreach($tabs_added as $key => $value){
    $tabs_added_array[] = $key;
}
$the_tabs = implode(',', $tabs_added_array);
var_dump($tabs_added_array);

There must be something else in the code you're not showing us whether you know it or not. 无论您是否知道,您的代码中肯定还有其他内容没有向我们显示。

I ended up doing this to fix my problem: 我最终这样做是为了解决我的问题:

foreach($tabs_added_array as $key => $val) {
    if(strlen($val) <= 3)
        unset($tabs_added_array[$key]);
}

Yes, it's a dirty fix. 是的,这是一个肮脏的解决方法。 But I didn't know how else to do it. 但是我不知道该怎么办。 It didn't fix the problem, but it's a solution. 它没有解决问题,但这是一个解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM