简体   繁体   English

在数组上使用unset(),但保留值

[英]Using unset() on an array, but it keeps the value

I'm trying to remove an object from an array if one of his properties is null or empty, this is the code. 我正在尝试从数组中删除对象,如果他的属性之一为null或为空,这就是代码。

The array has been sorted using this function: 使用以下函数对数组进行了排序:

function sortArray($c1, $c2)
{
    return ($c1->propertyToCheck < $c2->propertyToCheck);
}

In case it changes anything. 万一发生任何变化。

$myArray = array();
...
// Add values to the array here
...
usort($myArray,"sortArray");

for($i = 0; $i < count($myArray ); $i++)
{
    if(empty($myArray[$i]->propertyToCheck))
    {
        unset($myArray[$i]);

        // var_dump($myArray[$i]) returns NULL
    }
}

echo json_encode($myArray); 
// Returns the entire array, even with the values that shouldn't be there.

The code is inside a function but the array is created inside said function. 代码在函数内部,但是数组在所述函数内部创建。

I'm using echo json_encode($myArray) to send the value back in AJAX, but the array sent is the entire array with every object inside it. 我正在使用echo json_encode($ myArray)将值发送回AJAX,但是发送的数组是其中每个对象都包含的整个数组。

The count($myArray) is the "problem". count($myArray)是“问题”。
Once the unset() is "reached" there is one element less in the array and therefore the next call to count($myArray) will return n-1 of the previous iteration -> your loop doesn't get to the end of the array. 一旦unset()被“到达”,数组中的元素就会减少一个,因此下一次对count($myArray)调用将返回上一次迭代的n-1->您的循环不会到达数组。
You have at least three choices (in ascending order of my preference) 您至少有三个选择(按我的喜好升序)

a) 一种)

$maxIdx = count($myArray);
for($i = 0; $i < $maxIdx; $i++) {

b) b)

foreach( $myArray as $key=>$obj ) {
    if(empty($obj->propertyToCheck)) {
        unset($myArray[$key]);

c) C)

$myArray = array_filter(
    $myArray,
    function($e) {
        return !empty($e->propertyToCheck); 
    }
);

(...and many more) (...还有很多)

see also: http://docs.php.net/array_filter 另请参阅: http : //docs.php.net/array_filter

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

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