S
S
Stoble2021-06-06 18:12:28
PHP
Stoble, 2021-06-06 18:12:28

Why doesn't iteration work?

Fatal error: An iterator cannot be used with foreach by reference in D:\OpenServer\domains\Site\index.php on line 20

$query = "SELECT * FROM man_cats";
$result = mysqli_query($connect, $query);

function buildTree($result) {

    $childs = array();

    foreach($result as &$item) {
         $childs[$item['parent_id']][] = &$item;
         unset($item);
    }

    foreach($result as &$item) {
        if (isset($childs[$item['id']])) {
            $item['childs'] = $childs[$item['id']];
        }
    }
    return $childs[0];
}

buildTree($result);


Здесь начинается 20 строчка -
 foreach($result as &$item) {
         $childs[$item['parent_id']][] = &$item;
         unset($item);
    }

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Rsa97, 2021-06-06
@Stoble

If the SELECT, SHOW, DESCRIBE, or EXPLAIN queries succeed, mysqli_query() will return a mysqli_result object .

You are trying to work with this object as an array.

R
rPman, 2021-06-06
@rPman

&$item - remove &, you also don't need to unset (and in your case it's still a problem you try to save the pointer to item in the array and delete it right there), php has a good auto-garbage collector
return $childs[0] you return a null element collected array and the rest is cleared? is he there? here can without [0]?

V
Vitsliputsli, 2021-06-07
@Vitsliputsli

As written in the error: An iterator cannot be used with foreach by reference - the iterator cannot be used in foreach through a reference.
mysqli_query returns an iterable object i.e. an object that has a method to get an iterator that knows how to iterate the object. When iterating, foreach calls the corresponding iterator method, which returns the desired value. Because it's just a value, not a property of the object, you can't refer to it by reference.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question