检查Array中是否存在value,然后保存为变量



关于如何检查数组中是否存在值,如果存在,将其分配给要插入数据库的变量,已经尝试了一段时间。

我有搜索工作,虽然我似乎不能从数组中获取正确的值,然后我需要插入。

这里是我搜索ID的地方:

{
    "questionName": "_questionImgPhoto_176471",
    "questionID": "471",
}

下面是数组的例子:

[0]"/insert/ImgID_466.png"
[1]"/insert/ImgID_471.png"

我正在检查是否questionID 471存在于数组字符串的某个地方,如果是,插入该行。我在这方面很挣扎。

对于questionID 466的插入,字符串中有466的img将附加到它,以此类推

正如你所看到的,471确实存在于数组示例中,所以它应该抓取该行,下面是我的代码片段:

for ($i=0; $i < count($content->formValuesT); $i++) 
                    { 
                        if(strpos($content->formValuesT[$i]->questionValue, 'blob') !== false )
                            {
                                foreach($content->images_to_upload[$i] as $index => $string) {
                                    if (strpos($string, $content->formValuesT[$i]->questionID) !== FALSE)
                                    {
                                         $file_to_upload = $content->images_to_upload[$i];    
                                    }
                                    else
                                    {
                                        echo "wont insert";
                                    }
                                }
                            }
}

有没有人对如何实现上述目标有一些建议或想法?我只是无法理解它实际的一面!从理论上讲,我认为这是正确的路线。

$file_to_upload是每行上传的内容。

感谢

可以在数组中搜索特定的模式。这里我做了一个简单的辅助函数来返回第一个匹配或NULL。

$imagesToInsert = ["/insert/ImgID_466.png", "/insert/ImgID_471.png"];
$getImageForId = function(int $id, array $images): ?string {
    $matches = preg_grep("/ImgID_{$id}.png/", $images);
    return $matches ? reset($matches) : null;
};
var_dump($getImageForId(471, $imagesToInsert));
var_dump($getImageForId(466, $imagesToInsert));
var_dump($getImageForId(777, $imagesToInsert));

输出
string(21) "/insert/ImgID_471.png"
string(21) "/insert/ImgID_466.png"
NULL

最新更新