如何在php函数中返回数组

时间:2017-07-04 06:29:23

标签: javascript php ajax laravel intervention

我正在使用laravel 5.4和干预插件将图像上传为ajax

我将在php控制器上传图像,它将返回一个响应(文件名)。

并且来自php的返回变量是一个数组但是在javascript中它会变成字符串而我无法迭代那个

 public function upload(Request $request)
{
    $array = $request->file('image');
    $count = count($array);

    for ($i=0 ; $i<$count; $i++)
    {
        $img = Image::make($request->file('image')[$i]);
        $img->widen(800);
        $img->fit(800,600);
        $rnd = rand(10,10000);
        $location = 'images/carimages/c'.$rnd.'.jpg';
        $img->save($location);
        $answer[] = $rnd;
    }
    return $answer;
}

3 个答案:

答案 0 :(得分:0)

试试这个,

return response()->json($answer);

答案 1 :(得分:0)

尝试使用json_encode()

这将解决您的问题。

public function upload(Request $request)
{
    $answer=array();
    $array = $request->file('image');
    $count = count($array);

    for ($i=0 ; $i<$count; $i++)
    {
        $img = Image::make($request->file('image')[$i]);
        $img->widen(800);
        $img->fit(800,600);
        $rnd = rand(10,10000);
        $location = 'images/carimages/c'.$rnd.'.jpg';
        $img->save($location);
        $answer[] = $rnd;
    }
    echo json_encode($answer);
    die;
}

答案 2 :(得分:0)

public function upload(Request $request) {
    $answer=array();
    $array = $request->file('image');
    $count = count($array);
    $answer=array();
    for ($i=0 ; $i<$count; $i++)
    {
        $img = Image::make($request->file('image')[$i]);
        $img->widen(800);
        $img->fit(800,600);
        $rnd = rand(10,10000);
        $location = 'images/carimages/c'.$rnd.'.jpg';
        $img->save($location);
        $answer[$i] = $rnd;
    }
//here print $answer and check 
//you can also check $answer with function var_dump(); 
    echo json_encode($answer);
    die;
}

将此数组解码为

json_decode($json_array,true);