我需要在for()语句中使用OR(||)运算符,但它没有按预期工作。
我发送了4个附件。两个是内联图像,另外两个是实际附件。
问题是它只循环通过两个内联图像($results['Related'])
我想我的解决方案很简单,但我只是没有看到。
这是我的代码:
# Check for attachments
if(isset($results['Related']) || isset($results['Attachments']))
{
if(isset($results['Related']))
{
$attachment_type = $results['Related'];
}
elseif(isset($results['Attachments']))
{
$attachment_type = $results['Attachments'];
}
for($i = 0; ($i < count($results['Attachments']) || $i < count($results['Related'])); $i++)
{
# Format file name (change spaces to underscore then remove anything that isn't a letter, number or underscore)
$filename = preg_replace('/[^0-9,a-z,'.,_]*/i', '', str_replace(' ', '_', $attachment_type[$i]['FileName']));
/* LOTS MORE CODE HERE */
}
}
编辑:我忘了告诉你问题出在哪里了。
单独执行。
if(isset($results['Related']) {
foreach ($results['Related'] as &$el) {
$el['FileName'] = preg_replace('/[^0-9,a-z,'.,_]*/i', '', str_replace(' ', '_', $el['FileName']));
}
}
if(isset($results['Attachments']) {
foreach ($results['Attachments'] as &$el) {
$el['FileName'] = preg_replace('/[^0-9,a-z,'.,_]*/i', '', str_replace(' ', '_', $el['FileName']));
}
}
更新:
有几种方法可以做到这一点,但为了维护和可读性,我会选择基于array_walk()
的解决方案:
$doLotsOfStuff = function(&$el) {
$el['FileName'] = preg_replace('/[^0-9,a-z,'.,_]*/i', '', str_replace(' ', '_', $el['FileName']));
// Your other code goes here.
};
if (isset($results['Related'])) {
array_walk($results['Related'], $doLotsOfStuff);
}
if (isset($results['Attachments'])) {
array_walk($results['Attachments'], $doLotsOfStuff);
}
编辑:
对于不支持匿名函数的旧PHP版本,可以使用普通函数:
function doLotsOfStuff(&$el) {
$el['FileName'] = preg_replace('/[^0-9,a-z,'.,_]*/i', '', str_replace(' ', '_', $el['FileName']));
// Your other code goes here.
}
if (isset($results['Related'])) {
array_walk($results['Related'], 'doLotsOfStuff');
}
if (isset($results['Attachments'])) {
array_walk($results['Attachments'], 'doLotsOfStuff');
}
您在未设置的对象上调用count
,只需将$attachment_type
本身计算为保证已设置。
您需要对计数求和吗?
我猜count($results['Attachments'])
是2,count($results['Related'])
也是2,因为你说你每个发送两个。在这种情况下,它只会运行前两次。
听起来你需要这样的东西:
# Check for attachments
if(isset($results['Related']) || isset($results['Attachments']))
{
$count = 0;
if(isset($results['Related']))
{
$attachment_type = $results['Related'];
$count += count($results['Related']);
}
if(isset($results['Attachments']))
{
$attachment_type = $results['Attachments'];
$count += count($results['Attachments']);
}
for($i = 0; $i < $count; $i++)
{
# Format file name (change spaces to underscore then remove anything that isn't a letter, number or underscore)
$filename = preg_replace('/[^0-9,a-z,'.,_]*/i', '', str_replace(' ', '_', $attachment_type[$i]['FileName']));
}
}