user9530586
user9530586

Reputation: 13

Moving an array to the end of an array

So I'm trying to combine $gender and $grade and then remove them from the middle of my array and put them at the end. This is what I have so far but it adds both to the end but they're still in the middle of the output file. I feel like I'm missing something simple here. Any suggestions?

<?php

$inputFile = "Student_Data.csv";
$outputFile = "test.csv";

$count = 0; 

$out = fopen($outputFile, "w");
$in = fopen($inputFile, "r");

while ($row = fgetcsv($in)) {
    $gender = array($row[6]);
    $grade = array($row[7]);
    $merge = array_merge ($gender, $grade);
    $final = array_merge ($row, $merge);
    $sisline = implode(",", $final) . "\r\n";

    print_r ($sisline);
    $count++;
}

fclose($out);
fclose($in);


?>

Upvotes: 0

Views: 44

Answers (2)

Scuzzy
Scuzzy

Reputation: 12332

Once you extract the value, remove them from the soruce.

$gender = array($row[6]);
$grade = array($row[7]);
unset($row[6],$row[7]);

or to get fancy as single line solution.

$row = array_diff_key($row,array_flip(array(6,7))) + $row;

Upvotes: 1

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41820

Because the two keys you want are consecutive, you can select them and remove them in one step with array_splice

$genderAndGrade = array_splice($row, 6, 2);
$final = array_merge($row, $genderAndGrade);

Upvotes: 0

Related Questions