在关联数组数组中循环以删除某些数据会将错误的数据添加到第二项中


looping through array of associative arrays to remove some data adds wrong data to second item

这是对DB:的查询结果

array(2) {
    [0] array(21) {
        ["model_id"] 218
        ["total"] 10
        ["make"] "maker_a"
        ["model_name"] "some_name"
        ["picture"] "some_picture.jpg"
        ["color"] "Black"
        [1] 0
        [2] 0
        [3] 0
        [4] 6
        [5] 3
        [6] 1
        [7] 0
        [8] 0
        [9] 0
        [10] 0
        [11] 0
        [12] 0
        [13] 0
        [14] 0
        [15] 0
    }
    [1] array(21) {
        ["model_id"] 219
        ["total"] 10
        ["designer"] "maker_a"
        ["model_name"] "some_other_name"
        ["picture"] "some_other_picture.jpg"
        ["color"] "White"
        [1] 0
        [2] 0
        [3] 0
        [4] 5
        [5] 5
        [6] 0
        [7] 0
        [8] 0
        [9] 0
        [10] 0
        [11] 0
        [12] 0
        [13] 0
        [14] 0
        [15] 0
    }
}

我想去掉值为0的项目,所以我尝试了这个循环:

$results = [];
foreach ($models as $i) {
    foreach ($i as $key => $value) {
        if ($value != 0 || !is_numeric($value)) {
            $result[$key] = $value;
        }
    }
    if (isset($result)) {
        $results[] = $result;
    }
}
var_dump($results);

但由于某些原因,结果不正确,一个值为的项!=0被添加到第二个项中,而[6]1得到的值在第一个项中正确存在添加到只有[4]5和[5]5的第二项中。我不明白这个结果的原因。

array(2) {
    [0] array(9) {
        ["model_id"] 218
        ["total"] 10
        ["makes"] "maker_a"
        ["model_name"] "some_name"
        ["picture"] "some_picture.jpg"
        ["color"] "Black"
        [4] 6
        [5] 3
        [6] 1
    }
        [1] array(9) {
        ["model_id"] 219
        ["total"] 10
        ["designer"] "maker_a"
        ["model_name"] "some_other_name"
        ["picture"] "some_other_picture.jpg"
        ["color"] "White"
        [4] 5
        [5] 5
        [6] 1 <---- THIS DOESN'T BELONG HERE!
    }
}

该死,由于某种原因,循环将最后一个$result变量发布到下一项中。解决方案是在插入$results数组后添加unset($result);

$results = [];
    foreach ($models as $i) {
        foreach ($i as $key => $value) {
            if ($value != 0 || !is_numeric($value)) {
                $result[$key] = $value;
            }
        }
        if (isset($result)) {
            $results[] = $result;
            unset($result); // <--- HERE
        }
    }
    var_dump($results);