如何在PHP中的另一个关联数组中复制关联数组

时间:2022-04-15 08:24:27

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.

PS:我知道我不应该像这样循环SQL语句,但这是一个特例。

2 个解决方案

#1


2  

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循环中,你需要通过引用传递$ row变量,否则你只是从$ row中存储的$ rows修改元素的副本:

foreach($rows as &$row)

#2


0  

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>'; }

$ row ['NestedResults'] [] = $ row2; foreach($ row ['NestedResults']为$ results){echo $ results ['Item']。 “结果”; }

not 100% sure...

不是100%肯定......

#1


2  

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循环中,你需要通过引用传递$ row变量,否则你只是从$ row中存储的$ rows修改元素的副本:

foreach($rows as &$row)

#2


0  

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>'; }

$ row ['NestedResults'] [] = $ row2; foreach($ row ['NestedResults']为$ results){echo $ results ['Item']。 “结果”; }

not 100% sure...

不是100%肯定......