简体   繁体   English

PHP未设置未按预期工作

[英]PHP unset Not Working as expected

I am simply trying to remove all of the Array objects that have 'visible' set to '0' 我只是想删除所有将“可见”设置为“ 0”的数组对象

Array: 数组:

{
"Count":5,
"0":{"id":"1","visible":"0"},
"1":{"id":"3","visible":"0"},
"2":{"id":"1","visible":"0"},
"3":{"id":"2","visible":"0"},
"4":{"id":"3","visible":"0"}
}

PHP: PHP:

function cleanup($arr) {
    for($i = 0; $i < (count($arr)-1); $i++) {
        if($arr[$i]['visible'] == false) {
            unset($arr[$i]);
        }
    }
    $newarr = array_unique($arr, SORT_REGULAR);
    $newarr['Count'] = count($newarr)-1;

    return $newarr;
}

Result: 结果:

{
"Count":2,
"3":{"id":"2","visible":"0"},
"4":{"id":"3","visible":"0"}
}

In my mind this should work and return {"Count":0}. 在我看来,这应该起作用并返回{“ Count”:0}。 Also Why have the 'keys' not been set to 0,1 instead of 3,4. 还有为什么“键”没有设置为0,1而不是3,4。 Where am i going wrong? 我要去哪里错了?

You are using count($arr)-1) inside the for loop, and it gets re-evaluated every iteration, so after you unset the first three times, i is 3, but count($arr)-1) is 1, and you exit the loop. 您在for循环内使用count($ arr)-1),并且每次迭代都会对其进行重新评估,因此在取消设置前三次后,i为3,而count($ arr)-1)为1,然后退出循环。 You should set $j=count($arr)-1 before the for loop, and use for($i = 0; $i < $j; $i++) 您应该在for循环之前设置$ j = count($ arr)-1,并使用for($ i = 0; $ i <$ j; $ i ++)

In general it is bad programming practice (performance-wise) to use functions like count() inside the for loop 通常,在for循环中使用诸如count()之类的函数是不好的编程习惯(从性能角度而言)

unset() will not reorder the array indexes if you removing an index from the middle of an numerical array. 如果从数字数组的中间删除索引,则unset()不会对数组索引重新排序。 You need to reindex the array by yourself. 您需要自己重新索引数组。 array_values() is helpful here. array_values()在这里很有帮助。

function cleanup($arr) {
    for($i = 0; $i < (count($arr)-1); $i++) {
        if($arr[$i]['visible'] == false) {
            unset($arr[$i]);
        }
    }
    $newarr = array_values(array_unique($arr, SORT_REGULAR));
    return $newarr;
}

The Count property makes no sense for me therefore I dropped it away. Count属性对我来说毫无意义,因此我放弃了它。 You may use the function count() instead. 您可以改用count()函数。

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

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