开发者

array_diff & renumbering numeric keys

(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 o开发者_运维技巧ver the place.

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


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

$array = array_values($array);


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
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜