Search code examples
phpunset

Change Column Headers in Array with Unset: PHP


I'm trying to change the text that gets written to the first row, column header, of my csv. I'm trying to use unset, but it's not working. Am I referencing the wrong array? Any help would be appreciated. My code is below:

for ($x=0; $x<$count; $x++)
{
    $currentRecord = $response['data'][$x];
    $jsonDataInArray[] = array
    (
        "b98336b40c8420dc2f1401d6451b1b47198eee6d" => $response['data'][$x]['b98336b40c8420dc2f1401d6451b1b47198eee6d'],
        "17a14a9da9815451ff5ffc669d407e8b0376b06b" => $response['data'][$x]['17a14a9da9815451ff5ffc669d407e8b0376b06b'],
        "3eedd4fd08f44a72d911dc4934a6916f3b31911b" => $response['data'][$x]['3eedd4fd08f44a72d911dc4934a6916f3b31911b'],
        "52ede287f6c55eb6b12821ca24f74098779abdce" => $response['data'][$x]['52ede287f6c55eb6b12821ca24f74098779abdce'],
        "13916ba291ab595f27aefbff8b6c43a3fb467b72" => $response['data'][$x]['13916ba291ab595f27aefbff8b6c43a3fb467b72']
    )
)

//change key names.
$jsonDataInArray["Col1"] = $jsonDataInArray["b98336b40c8420dc2f1401d6451b1b47198eee6d"];
unset($jsonDataInArray["b98336b40c8420dc2f1401d6451b1b47198eee6d"]);

//first row of data 
$test_array = $jsonDataInArray[0];



//open file to write towards
if($startPos == 0){
    $fp = fopen('output.csv', 'w');
    fputcsv($fp, array_keys($response['data'][0]));
}else{
    $fp = fopen('output.csv', 'a');
}

//write data
foreach ($jsonDataInArray as $fields)
{
    fputcsv($fp, $fields);
}

My current output is:

b98336b40c8420dc2f1401d6451b1b47198eee6d|17a14a9da9815451ff5ffc669d407e8b0376b06b|3eedd4fd08f44a72d911dc4934a6916f3b31911b|52ede287f6c55eb6b12821ca24f74098779abdce
4616|||stuff

My desired output would be

Col1|17a14a9da9815451ff5ffc669d407e8b0376b06b|3eedd4fd08f44a72d911dc4934a6916f3b31911b|52ede287f6c55eb6b12821ca24f74098779abdce
4616|||stuff

Solution

  • Your $jsonDataInArray has numerical indexes, each of which contains an array.

    Replace

    $jsonDataInArray["Col1"] = $jsonDataInArray["b98336b40c8420dc2f1401d6451b1b47198eee6d"];
    unset($jsonDataInArray["b98336b40c8420dc2f1401d6451b1b47198eee6d"]);
    

    with

    $jsonDataInArray[0]["Col1"] = $jsonDataInArray[0]["b98336b40c8420dc2f1401d6451b1b47198eee6d"];
    unset($jsonDataInArray[0]["b98336b40c8420dc2f1401d6451b1b47198eee6d"]);
    

    to have it work in your test, but you'll probably want to replace that with a loop to have it change for each entry.