我需要在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 */
}
}
编辑:我忘了告诉你问题是什么。
答案 0 :(得分:2)
单独进行。
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']));
}
}
答案 1 :(得分:1)
<强>更新强>
有几种方法可以做到,但为了可维护性和可读性,我会选择基于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');
}
答案 2 :(得分:0)
你需要总结一下吗?
我猜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']));
}
}
答案 3 :(得分:0)
您正在对未设置的内容调用count
,只需计算$attachment_type
本身就可以确保设置。