【发布时间】:2019-03-31 09:43:14
【问题描述】:
我有 2 个数组,$fileArr 和 $noteArr。
$fileArr 是一个文件列表。一个文件可以链接到多个故事。所以在这个$fileArr 中,你会看到我需要列出的每个故事的所有文件。请注意,CAR.jpg ([processId]=>111) 链接到 [storyId]=>1 和 [storyId]=>2。所以 CAR.jpg 将被列出两次。
我想从$noteArr 中取出所有笔记,并通过匹配[processId 将它们放入$fileArr。所以 CAR.jpg 的每个实例都有 2 个音符,而 TRUCK.jpg 没有。
我当前的 $fileArr
Array
(
[0] => Array
(
[fileName] => CAR.jpg
[processId] => 111
[storyId] => 1
)
[1] => Array
(
[fileName] => CAR.jpg
[processId] => 111
[storyId] => 2
)
[2] => Array
(
[fileName] => TRUCK.jpg
[processId] => 222
[storyId] => 3
)
)
我现在的 $noteArr
Array
(
[0] => Array
(
[noteId] => 50
[note] => this is a note
[processId] => 111
)
[1] => Array
(
[noteId] => 51
[note] => and this is also a note
[processId] => 111
)
)
我想要的新数组,通过匹配 processId 放置在文件下的注释
Array
(
[0] => Array
(
[fileName] => CAR.jpg
[processId] => 111
[storyId] => 1
[notes] => Array
(
[50] => Array
(
[noteId] => 50
[note] => this is a note
[processId] => 111
)
[51] => Array
(
[noteId] => 51
[note] => and this is also a note
[processId] => 111
)
)
)
[1] => Array
(
[fileName] => CAR.jpg
[processId] => 111
[storyId] => 2
[notes] => Array
(
[50] => Array
(
[noteId] => 50
[note] => this is a note
[processId] => 111
)
[51] => Array
(
[noteId] => 51
[note] => and this is also a note
[processId] => 111
)
)
)
[2] => Array
(
[fileName] => TRUCK.jpg
[processId] => 222
[storyId] => 3
)
)
我可以通过我在下面编写的代码完成此操作,但不想在循环中使用循环。还有其他方法可以实现吗?
我当前的代码(循环内循环)
$newArr = array();
$i = 0;
foreach($fileArr as $file){
$newArr[$i] = $file;
if(count($noteArr)>0){
foreach($noteArr as $note){
if($file['processId']==$note['processId']){
$newArr[$i]['notes'][$note['id']] = $note;
}
}
}
$i++;
}
【问题讨论】:
-
问题,你为什么不想使用嵌套循环?
-
嗨@Difster,有人告诉我,由于复杂性和陷入永无止境的循环的可能性,在必要时应避免嵌套循环。我知道有时需要它们,但如果有一个实例我可以使用另一种解决方案,我通常会走这条路。您认为这是必要的情况吗?
-
@jmchauv 您不应该陷入使用 foreach 的永无止境的循环中,因为它只是从第一个元素迭代到最后一个元素。
标签: php arrays loops multidimensional-array foreach