0

I'm new to laravel, and I'm making an app that need a .CSV data to be imported into the database, the data has been succesfully imported however i faced this issue :

ErrorException array_combine(): Both parameters should have an equal number of elements

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Accounts;
class AccountController extends Controller
{
    public function show(){
        return view ('upload');
    }
    public function store(Request $request){


        $file = $request->file('upload-file');
        $csvData = file_get_contents($file);

        $rows = array_map("str_getcsv", explode("\n", $csvData));
    // dd($rows);
        $header = array_shift($rows);
//    dd($header);
        foreach ($rows as $row) {

            $row = array_combine($header, $row);
            if (count($header) != count($row)) {
                continue;
              }
            set_time_limit(0);
            Accounts::create([
                'AccountClass' => $row['Classe'],
                'AccountNumber' => $row['Compte'],
                'AccountDesc' => $row['Desc'],
                'active' => 1,
            ]);
        }

        return view ('home');

    }

}

would you point me to the right direction thank you in advance

2

1 Answer 1

1

This error appears when you try to combine two arrays with unequal length.

$arr1 = ["a", "s", "d"];
$arr2 = [1, 2, 3];

if(count($arr1) == count($arr2)){
    $result = array_combine($arr1, $arr2);
} else{
    echo "Error array combine";
}
Sign up to request clarification or add additional context in comments.

2 Comments

i have first array 0 => "1" 1 => "1" 2 => "COMPTES DE FINANCEMENT PERMANENT" and second array array:3 [▼ 0 => "Classe" 1 => "Compte" 2 => "Desc" ] ;i guess they are equal
@anabel the problem is that you have duplicate values for keys, array_combine() tries to take values from the first array as keys and the values from the second array as values of the new array, i.e. tries to do this 1 => "Classe" 1 => "Compte" "COMPTES DE FINANCEMENT PERMANENT" => "Desc" The problem here is that you have duplicate keys (1 being duplicate)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.