ana bel
ana bel

Reputation: 187

remove null from an array

i want to import csv to database , how ever i got this error : code : ErrorException array_combine(): Both parameters should have an equal number of elements i know that the error shows that the two arrays arent in the same length how ever i couldnt find a solution to remove the null value from an array

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);

        foreach ($rows as $row) {


            $row = array_combine($header, $row);



            set_time_limit(0);
            Accounts::create([
                'AccountClass' => $row['Classe'],
                'AccountNumber' => $row['Compte'],
                'AccountDesc' => $row['Desc'],
                'active' => 1,
            ]);
        }

        return view ('home');

    }

}

Result: header :

array:3 [▼
  0 => "Classe"
  1 => "Compte"
  2 => "Desc"
]

rows :

   array:4 [▼
      0 => array:3 [▼
        0 => "1"
        1 => "1"
        2 => "COMPTES DE FINANCEMENT PERMANENT"
      ]
      1 => array:3 [▼
        0 => "1"
        1 => "11"
        2 => "CAPITAUX PROPRES"
      ]
      2 => array:1 [▼
        0 => null
      ]
    ]

But I want

   array:4 [▼

          0 => array:3 [▼
            0 => "1"
            1 => "1"
            2 => "COMPTES DE FINANCEMENT PERMANENT"
          ]
          1 => array:3 [▼
            0 => "1"
            1 => "11"
            2 => "CAPITAUX PROPRES"
          ]
        ]

Any advice greatly appreciated.

Upvotes: 0

Views: 107

Answers (2)

Digvijay
Digvijay

Reputation: 8927

Since laravel is tagged on this question, might I suggest using collection.

$array = [1, 2, 3, null, 4];
$array = collect($array)->filter()->values()->toArray();

Here, filter() will remove null values and value() will re-index your array.
Hope it helps. Cheers.

Upvotes: 1

Jithesh Jose
Jithesh Jose

Reputation: 1814

Try

$res = [];
foreach($x as $key => $value)
{
if($value[0] == null)
unset($x[$key]);
else
$res[$key] = $value;
}
print_r($res);

Output will be

Array
(
[0] => Array
    (
        [0] => 1
        [1] => 1
        [2] => COMPTES DE FINANCEMENT PERMANENT
    )

[1] => Array
    (
        [0] => 1
        [1] => 11
        [2] => CAPITAUX PROPRES
    )

)

Upvotes: 2

Related Questions