我正在做什么:我有一个包含#项目的txt文件。我还有一个图像目录,其中包含这些项目#' s作为其文件名的前缀,但也有一些其他字符串(由-
分隔),然后是文件扩展名(.jpg
)。
问题:我的功能运行良好,但结果数组($overlap
)需要采用图片原来的格式,因为我要去将此数组写入CSV文件,以便我可以导入它。但是为了找到匹配项,我不得不在图像文件名上删除原始格式(所以array_intersection()
会起作用),但现在我需要恢复它。
以下是当前代码:
function test() {
function sanitize_items($value) {
# Convert to uppercase, remove whitespace, then remove .JPG extension.
# If the name has a "-", return the part before it.
$base = basename( trim(strtoupper($value)), '.JPG' );
$temp = explode('-', $base);
return $temp[0];
}
$file = file('items.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$img = scandir('img');
$file = array_map('sanitize_items', $file);
$img = array_map('sanitize_items', $img);
$overlap = array_intersect($file, $img);
echo "<pre>";
print_r($overlap); # returns the matches, but not in the format I need.
}
这是$overlap
当前返回的内容:
Array
(
[0] => DEC308A
[1] => DEC308B
[2] => DEC309A
...
)
我需要它来返回交叉点但是在sanitize_items()
运行之前的方式:
Array
(
[0] => DEC308A-2020.jpg
[1] => DEC308B-2020.jpg
[2] => DEC309A-2300.jpg
...
)
答案 0 :(得分:3)
我建议不要使用array_map()
(不能保留数组键)来应用您的清理函数,而是建议在两个输入上执行foreach()
循环以生成一个新数组字符串如DEC308A
作为关联数组键,原始的完整.jpg
字符串作为其值。然后,您可以在它们之间调用array_intersect_key()
以生成交叉点输出,该输出具有缩短/消毒的字符串(在键中)和原始字符串(在值中)。
// Keep this function as it is...
function sanitize_items($value) {
# Convert to uppercase, remove whitespace, then remove .JPG extension.
# If the name has a "-", return the part before it.
$base = basename( trim(strtoupper($value)), '.JPG' );
$temp = explode('-', $base);
return $temp[0];
}
$file = file('items.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$img = scandir('img');
// Temporary sanitized arrays:
$file_sanitized = array();
$img_sanitized = array();
// Loop over the input arrays and store them as key => value
// pairs, where the sanitized string is the key
foreach ($file as $f) {
// Produces $file_sanitized['DEC308A'] = 'DEC308A-2020.jpg';
$file_sanitized[sanitize_items($f)] = $f;
}
// Same kind of thing for $img...
foreach ($img as $i) {
$img_sanitized[sanitize_items($i)] = $i;
}
// Now compare for intersection by key
$overlap = array_intersect_key($file_sanitized, $img_sanitized);
//--------------------------------
// Note, not sure of your inputs but you might need to reverse the args favoring
// $img_sanitized so you get those resultant values rather than what was in the file...
// $overlap = array_intersect_key($img_sanitized, $file_sanitized);
echo "<pre>";
print_r($overlap);
如果你真的想要最后的普通数字键,而不是DEC308A
之类的字符串,只需在其上调用array_values()
:
$overlap = array_values($overlap);