Skip to content
Advertisement

Modifying the keys in a PHP array before sending to JSON

I am querying a SQL database and returning some values. What I have is Field1 and Field2 which come out with a list of dates (There may be up to 200 values/dates eventually). I then reformat the current dates into the desired format.

// While we have valid rows
while( $row = sqlsrv_fetch_array($rs, SQLSRV_FETCH_ASSOC)) {

    //build an array of all fields and their values
    $outputstring[] = $row; 
}

// for each record, IF the fields exist, reformat the date  
foreach($outputstring as &$each) {
    if($each['Field1']) $each['Field1'] = $each['Field1']->format('m-d H:i');
    if($each['Field2']) $each['Field2'] = $each['Field2']->format('m-d H:i');
}       

// Output as JSON   
echo JSE($outputstring);  

What I now want to do is change the names of Field1 and Field2 without modifying the SQL query and before the array is parsed as JSON.

I would normally just modify the SQL with;

Select Field1 as startdate, Field2 as enddate 

But this isn’t an option here as the value to be used must come from a translation function.

In the final output, Field1 needs to be displayed as the output of

lang('Field1');

This function delivers the translation of the field names in one of 33 languages depending on what the user selected prior to the output being generated.

I could use something like:

SELECT Field1 as ". lang('Field1') .", Field2 as ". lang('Field2') ."

but would prefer a PHP option that applies the language value to all keys in the array. As mentioned, there may be hundreds of fields in the final version and I don’t really want to hardcode each possible value if it can be avoided.

any ideas?

Advertisement

Answer

If I understand it correctly, can you use this?

$formatted = [];
while( $row = sqlsrv_fetch_array($rs, SQLSRV_FETCH_ASSOC)) {
    foreach($row as $key => $value) {
        $formatted[lang($key)] = $value->format('m-d H:i');
    }
}
// Output as JSON   
echo JSE($formatted);  
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement