forEach跳过循环中的最后一个元素

时间:2014-06-25 18:10:52

标签: php

我循环遍历countries个对象。但是,当我引用该对象时,我注意到倒数第二个元素是重复的,而跳过最后一个元素。乌拉圭出现两次,而美国根本没有出现。:

foreach($countries as &$country){
    $country->keywords = array_merge(array($country->name),$country->synonyms);
    var_dump($country->key);
}

var_dump('-----------------------------------------');

foreach($countries as $country){
    var_dump($country->key);
}

exit;

我的输出。一直滚动到底部,看uruguay现在出现两次:

string(7) "algeria"
string(9) "argentina"
string(9) "australia"
string(7) "belgium"
string(6) "bosnia"
string(8) "cameroon"
string(5) "chile"
string(8) "columbia"
string(9) "costarica"
string(5) "ivory"
string(7) "croatia"
string(8) "ecquador"
string(7) "england"
string(6) "france"
string(7) "germany"
string(5) "ghana"
string(6) "greece"
string(8) "honduras"
string(4) "iran"
string(5) "italy"
string(5) "japan"
string(6) "mexico"
string(11) "netherlands"
string(7) "nigeria"
string(8) "portugal"
string(6) "russia"
string(5) "korea"
string(5) "spain"
string(11) "switzerland"
string(7) "uruguay"
string(7) "america"
string(41) "-----------------------------------------"
string(7) "algeria"
string(9) "argentina"
string(9) "australia"
string(7) "belgium"
string(6) "bosnia"
string(8) "cameroon"
string(5) "chile"
string(8) "columbia"
string(9) "costarica"
string(5) "ivory"
string(7) "croatia"
string(8) "ecquador"
string(7) "england"
string(6) "france"
string(7) "germany"
string(5) "ghana"
string(6) "greece"
string(8) "honduras"
string(4) "iran"
string(5) "italy"
string(5) "japan"
string(6) "mexico"
string(11) "netherlands"
string(7) "nigeria"
string(8) "portugal"
string(6) "russia"
string(5) "korea"
string(5) "spain"
string(11) "switzerland"
string(7) "uruguay"
string(7) "uruguay"

1 个答案:

答案 0 :(得分:2)

foreach($countries as &$country){
    $country->keywords = array_merge(array($country->name),$country->synonyms);
    var_dump($country->key);
}
unset($country);

var_dump('-----------------------------------------');

foreach($countries as $country){
    var_dump($country->key);
}