如何从foreach循环中将字符串存储到数组中?

问题描述 投票:1回答:1

首先,我已经阅读了一些问题,在这里提出了类似的问题,但我没有采取任何例子并在我的代码中正确实现。我有一个包含几千个数字的数组,它们是目录中文件的名称。我需要运行一个MySQL Query来搜索那些文件名,但是我需要将所有单个查询都放在另一个数组中。

这是我获取文件名的代码:

$dir = "C:/Users/EyeCandy-Brian/Desktop/jobs";

$files = array_diff(scandir($dir), array('..', '.'));

function truncate(&$fcn) {
     $fcn = substr($fcn, 0, 6); // The original is '100100.dat', I only need the number
};

array_walk($files, "truncate");

该数组如下所示:

2 => string '100100'
3 => string '100101'
4 => string '100102'
5 => string '100103'
// About 1,500+ Total

这是我的foreach循环与我声明的变量:

$limit = 0; // This is for testing, stops after 5 iterations.
$qryArrNum = 2; // The index for the $files array, [0] & [1] were '.' & '..'
$count = 0; // Which index I want to store the string in, starting at [0]

$qry = array(); // I declare $qry as an array

foreach ($files as &$qry) {
    $qry[$count++] = "SELECT * FROM `table` WHERE `sku` LIKE '%$files[$qryArrNum]%'";
    ++$qryArrNum;
    if (++$limit == 5) {
        break;
    };
};

这是它变得疯狂的地方。当使用var_dump($qry);时,我得到的'1001S4'不应该。运行var_dump($files);数组的前五个字符串是:

2 => string 'S00100'
3 => string '1S0101'
4 => string '10S102'
5 => string '100S03'
6 => string '1001S4'

然后是文件名中的预期字符串:

7 => string '100105'
8 => string '100106'
9 => string '100107'
// On for 1,500+ again

所以我的问题是,如何让$qry成为一个包含字符串的数组,每个字符串都是包含从$files搜索第一个值的MySQL Query,而$qry数组中的下一个字符串将从中搜索下一个值$files。另外,为什么$files中的第一批少数值与预期完全不同?

注意:据我所知,按顺序运行一千多个MySQL查询将谋杀我的服务器,我将使用implode();将它们组合成一个大型查询,我只需要初步解决这个问题。

php mysql arrays foreach
1个回答
1
投票

您可以使用mysql find_in_set()而不是运行多个查询。 https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_find-in-set获得文件后,使用implode转换为字符串

$tmp = implode(",",$files);

你的sql语句是:

$sql = "SELECT * FROM `table` WHERE FIND_IN_SET(`sku`,'{$tmp}')>0";

这将返回所有匹配的项目

© www.soinside.com 2019 - 2024. All rights reserved.