【问题标题】:Using unset() on an array, but it keeps the value在数组上使用 unset(),但它保留了值
【发布时间】:2015-10-01 03:00:16
【问题描述】:

如果他的属性之一为空或空,我正在尝试从数组中删除一个对象,这就是代码。

数组已使用此函数排序:

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

万一它改变了什么。

$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.

代码在函数内部,但数组是在所述函数内部创建的。

我正在使用 echo json_encode($myArray) 将值发送回 AJAX,但发送的数组是包含每个对象的整个数组。

【问题讨论】:

  • 当我看到 for() 在数组上循环而不是 foreach() 时,我总是感到困惑
  • php 保留数字索引,你确定前后项的数量相同吗?

标签: php arrays ajax unset


【解决方案1】:

count($myArray) 是“问题”。
一旦 unset() 被“到达”,数组中就会少一个元素,因此下一次调用 count($myArray) 将返回上一次迭代的 n-1 -> 你的循环不会到达数组的末尾。
你至少有三个选择(按我的偏好升序排列)

一)

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

b)

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

c)

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

(……还有更多)

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

【讨论】:

    猜你喜欢
    • 2021-03-25
    • 1970-01-01
    • 2014-06-20
    • 1970-01-01
    • 2015-01-19
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    • 2019-11-19
    相关资源
    最近更新 更多