我有保存在数据库和服务器上的图像。我必须从数据库中获取图像,并将它们与服务器上的图像进行比较。如果匹配,则显示图像(使用匹配的图像名称创建新阵列并在浏览器中获取(
示例:
$db_image_array
Array
(
[0] => Array
(
[id] => 14
[eid] => 27
[stype_id] => 1 // folder1
[ihash] => oOYvcSEGeUjDpL2a.jpg
)
[1] => Array
(
[id] => 19
[eid] => 27
[stype_id] => 3 // folder3
[ihash] => XYmpP49Z5ye2OTL8.jpg
)
[2] => Array
(
[id] => 20
[eid] => 27
[stype_id] => 1 // folder1
[ihash] => uqF6whY6F6zNmdC7.jpg
)
[3] => Array
(
[id] => 21
[eid] => 27
[stype_id] => 1 // folder1
[ihash] => KXuYIidPpHrkZc96.jpg
)
)
$serverFolderArray
Array
(
[folder1] => Array
(
[0] => SplFileInfo Object
(
[pathName:SplFileInfo:private] => /var/www/vhosts/img/1629973f75566aed/folder1/uqF6whY6F6zNmdC7.jpg
[fileName:SplFileInfo:private] => uqF6whY6F6zNmdC7.jpg
)
[1] => SplFileInfo Object
(
[pathName:SplFileInfo:private] => /var/www/vhosts/img/1629973f75566aed/folder1/oOYvcSEGeUjDpL2a.jpg
[fileName:SplFileInfo:private] => oOYvcSEGeUjDpL2a.jpg
)
[2] => SplFileInfo Object
(
[pathName:SplFileInfo:private] => /var/www/vhosts/img/1629973f75566aed/folder1/KXuYIidPpHrkZc96.jpg
[fileName:SplFileInfo:private] => KXuYIidPpHrkZc96.jpg
)
)
[folder2] => Array
(
)
[folder3] => Array
(
[0] => SplFileInfo Object
(
[pathName:SplFileInfo:private] => /var/www/vhosts/img/1629973f75566aed/folder3/XYmpP49Z5ye2OTL8.jpg
[fileName:SplFileInfo:private] => XYmpP49Z5ye2OTL8.jpg
)
)
[folder4] => Array
(
)
)
我的第一次尝试是这个代码:
if ($db_image_array) {
foreach ($serverFolderArray as $arrayName => $serverImageArray) {
if ( ! empty($serverImageArray)) {
for ($y = 0; $y < count($db_image_array); $y++) {
for ($x = 0; $x < count($serverImageArray); $x++) {
if ($serverImageArray[$x]->getFilename() === $db_image_array[$y]['ihash']) {
$arr[$x] = $db_image_array[$y]['ihash'];
$chunked_array[$arrayName] = array_chunk($arr, 4);
}
}
}
}
}
}
还有第二次尝试使用foreach
循环:
if ( ! empty($serverImageArray)) {
for ($x = 0; $x < count($serverImageArray); $x++) {
foreach ($db_image_array as $key => $val) {
if ($serverImageArray[$x]->getFilename() === $val['ihash']) {
$arr[$x] = $val['ihash'];
$chunked_array[$arrayName] = array_chunk($arr, 4);
break;
}
}
}
}
两种方式都给了我wrond图像排序chunked_array
:
Array
(
[folder1] => Array
(
[0] => Array
(
[0] => oOYvcSEGeUjDpL2a.jpg
[1] => uqF6whY6F6zNmdC7.jpg
[2] => KXuYIidPpHrkZc96.jpg
)
)
[folder3] => Array
(
[0] => Array
(
[0] => oOYvcSEGeUjDpL2a.jpg // this one has not to be here
[1] => XYmpP49Z5ye2OTL8.jpg
[2] => KXuYIidPpHrkZc96.jpg // and this one also doesn't have to be in this array
)
)
)
你如何看待这种情况?逻辑错误在哪里?
所以,我与这个错误斗争了几个小时,但在创建这个主题30分钟后发现了一个逻辑错误,每次出现新的数组名称时,我都必须清除$arr
:
$arr=[]; // <---- !!!
if ( ! empty($serverImageArray)) {
for ($x = 0; $x < count($serverImageArray); $x++) {
foreach ($db_image_array as $key => $val) {
if ($serverImageArray[$x]->getFilename() === $val['ihash']) {
$arr[$x] = $val['ihash'];
$chunked_array[$arrayName] = array_chunk($arr, 4);
}
}
}
}