【问题标题】:array_push() expects parameter 1 to be array null givenarray_push() 期望参数 1 是给定的数组 null
【发布时间】:2019-06-01 13:04:36
【问题描述】:

我正在尝试使用此控制器代码将表单数据存储到内部 JSON 文件中

function index() {
  return view('contact_form');
}

function store(Request $request) {

    try {
        // my data storage location is project_root/storage/app/data.json file.
        $contactInfo = Storage::disk('local')->exists('data.json') ? json_decode(Storage::disk('local')->get('data.json')) : [];

        $inputData = $request->only(['name', 'email', 'message','subject']);

        $inputData['datetime_submitted'] = date('Y-m-d H:i:s');

        array_push($contactInfo,$inputData);

        Storage::disk('local')->put('data.json', json_encode($contactInfo));

        return $inputData;

    } catch(Exception $e) {

        return ['error' => true, 'message' => $e->getMessage()];

    }
}

但它仍然返回此错误

array_push() 期望参数 1 为数组 null 给定

我确定这是一个非常简单的错误,但我需要一些帮助来纠正它

【问题讨论】:

  • 很明显,$contactInfonull,这表明Storage::disk('local')->get('data.json') 正在返回"null"。 (旁注:最好只发出存储请求一次而不是两次?)如果不知道更多信息,我们无法告诉您为什么它为空。但这类事情最好通过调试解决,而不是通过 SO 问题。

标签: php json laravel-5


【解决方案1】:

data.json 存在但为空或包含无效 JSON。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    • 2015-08-25
    • 1970-01-01
    • 2014-06-28
    • 2021-12-29
    • 1970-01-01
    相关资源
    最近更新 更多