【发布时间】:2026-01-26 03:55:01
【问题描述】:
谁能帮助我解决为什么我的 array_search 在我编写的这个 PHP 脚本中不起作用。我已经搞砸了好几天,无法弄清楚这个问题。我已经尝试将array_search 移动到整个地方,循环内,循环外,我得到了相同的结果。我尝试搜索不同的数组值,尝试包含我自己的函数来搜索我在网上找到的数组。我知道这些值在数组中,因为我将数组打印到 .txt 文件中进行调试,现在我不知道接下来要查找什么。有任何想法吗?
<?php
//this variable tells us how many drupal nodes or 'paystub pages' we need to create
$nodeCount = 0;
$i = 0;
//needed for creating a drupal node
//for this code to work this script must be run from the root of the drupal installation
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
if ($handle = opendir('/var/www/html/pay.*********group.com/upload'))
{
/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$nodeCount++;
//We convert the pdf documents into text documents and move put them in the converted folder
$command = "pdftotext /var/www/html/pay.*********group.com/upload/" . $file . " /var/www/html/pay.*********group.com/upload/converted/" . $file . ".txt";
//Execute the command above
$output = exec($command);
}
}
closedir($handle);
}
//subtract two because the folders "array" and "converted" are included because PHP does not differentiate
//between folders and files
$nodeCount = $nodeCount - 2;
echo "<br />";
echo "<b> $nodeCount pdf files converted </b>";
echo "<br />";
//open the directory
if ($handle2 = opendir('/var/www/html/pay.*********group.com/upload/converted'))
{
//check to see if we have reached the last file of our directory, if not stay in loop
while (false !== ($currentText = readdir($handle2)))
{
//filter out files named . and ..
if ($currentText != "." && $currentText != "..")
{
//Create a file for array to be printed to
$createArray = fopen("/var/www/html/pay.*********group.com/upload/arrays/" . $currentText, "w+") or die ("Cannot find file to create array, ID 2");
//read the file we are on from the loop into the array
$currArray = file("/var/www/html/pay.*********group.com/upload/converted/" . $currentText) or die ("Cannot find file to create array, ID 1");
$ArrSearch = array_search("EMPLOYEE NO. ", $currArray);
echo "<br />";
echo "<b> $ArrSearch index found </b>";
echo "<br />";
//array_trim($currArray[$i]);
//var_dump($currArray[$i]);
//print array to .txt file for debugging purposes
$out = print_r($currArray, true);
fwrite($createArray, $out);
fclose($createArray);
$i++;
}
}
}
?>
编辑:我根据您的结论修复了代码,我也在这里更新了代码。使用上面的代码,这是我在尝试转换 6 个 pdf 文件时得到的输出。在每个索引旁边,我应该有一个来自每个搜索的数组索引
6 pdf files converted
index found
index found
index found
index found
index found
index found
【问题讨论】:
-
究竟是什么不起作用?您能否隔离您正在搜索的内容、文件中的内容以及不匹配的内容?这比一大段代码更有效。
-
我认为你在争论中改变了针和大海捞针...
$ArrSearch = array_search("EMPLOYEE NO. ", $currArray); -
@Brad 您应该将其添加为答案
-
The documentation 拥有解决问题所需的一切。