Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/252.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP函数将元素存储在数组中_Php_Arrays - Fatal编程技术网

PHP函数将元素存储在数组中

PHP函数将元素存储在数组中,php,arrays,Php,Arrays,我使用的是前端Javascript文本编辑器,它以html格式提交数据,还将所有图像转换为base64编码格式 下面的函数将为html内容解析$\u POST super global,并将编码图像及其相应的扩展名存储在images文件夹中 $html = preg_replace_callback("/src=\"data:([^\"]+)\"/", function ($matches) { list($contentType, $encContent) = explode(';',

我使用的是前端Javascript文本编辑器,它以html格式提交数据,还将所有图像转换为base64编码格式

下面的函数将为html内容解析$\u POST super global,并将编码图像及其相应的扩展名存储在images文件夹中

$html = preg_replace_callback("/src=\"data:([^\"]+)\"/", function ($matches) {
    list($contentType, $encContent) = explode(';', $matches[1]);
    if (substr($encContent, 0, 6) != 'base64') {
        return $matches[0];
    }
    $imgBase64 = substr($encContent, 6);
    $imgFilename = md5($imgBase64); // Get unique filename
    $imgExt = '';
    switch($contentType) {
        case 'image/jpeg':  $imgExt = 'jpg'; break;
        case 'image/gif':   $imgExt = 'gif'; break;
        case 'image/png':   $imgExt = 'png'; break;
        default:            return $matches[0]; 
    }

   // Here is where I'm able to echo image names with thier extentions.
   echo $imgFilename . '.' . $imgExt;

    $imgPath = 'zendesk-images/'.$imgFilename.'.'.$imgExt;
    // Save the file to disk if it doesn't exist
    if (!file_exists($imgPath)) {
        $imgDecoded = base64_decode($imgBase64);
        $fp = fopen($imgPath, 'w');
        if (!$fp) {
            return $matches[0];
        }
        fwrite($fp, $imgDecoded);
        fclose($fp);
    }
    return 'src="'.$imgPath.'"';
}, $html);
我可以在下面的行中回显图像名称

echo $imgFilename . '.' . $imgExt;
我正在尝试将转换后的图像文件名存储在一个数组中,但没有成功

下面是我尝试过的,在函数之前初始化一个数组

$Images = array(); 
然后,我没有回应,而是试着做以下的事情

$Images[] = $imgFilename . '.' . $imgExt; 

但这不起作用,我最终得到了空数组

如果你想在外部范围中使用$images,你需要

$images = array();
$html = preg_replace_callback("/src=\"data:([^\"]+)\"/", function ($matches) use(&$images) {
    //...
    $images[] = $imgFilename . '.' . $imgExt;
    //...
}
echo implode(', ', $images);

php变量区分大小写
$Images
$Images
是两个完全不同的变量。请注意,如果您尝试$Images[]=$imgFilename'.'$imgExt,然后必须有$images=array();而不是$Images=array();我相信如果在调用preg_replace_callback()之前声明$images=array(),那么$images[]=。。。超出此范围,将无法使用(&$images)访问$images…函数($matches){..@JurgisGregov Dam不知道它对内部函数有效:)您应该将此作为答案发布,以便OP能够将其设置为MVA