spiff
spiff

Reputation: 328

How to copy an associative array inside another associative array in PHP

Can anyone tell me how to store an array of associative arrays? I thought this code would work, but it's not. I tried researching it but couldn't find an answer.

foreach($rows as $row) {
    // Some SQL...
    if ($stmt->execute()) {
        while ($row2 = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $row['NestedResults'][] = $row2;
        }
    }
}

foreach ($rows as $row) {
    foreach ($row['NestedResults'] as $results) {
        echo $results['Item'] . '<br>';
    }
}

PS: I know I shouldn't loop SQL statements like that, but it's a special case.

Upvotes: 0

Views: 385

Answers (2)

Vinci321
Vinci321

Reputation: 11

do you think it is workable to put the second loop inside the first one as below?

$row['NestedResults'][] = $row2; foreach ($row['NestedResults'] as $results) { echo $results['Item'] . '<br>'; }

not 100% sure...

Upvotes: 0

Enstage
Enstage

Reputation: 2126

In your first foreach loop, you need to pass the $row variable by reference, otherwise you are just modifying a copy of the element from $rows stored in $row:

foreach($rows as &$row)

Upvotes: 2

Related Questions