Home > PHP, Tips > function array_flatten

function array_flatten

This is not much to brag about, still we had a very large dataset as variable dimensional and variable depth, which we wanted to be sent to a custom function using prototype.js. For the data exchange we use JSON, but the varying depth and related tags, made us to do like hell in the javascript templating that we had to find a method to flatten the array in such a way that each of the associative keys would not be mangled.

The final out come is function array_flatten


function array_flatten($p, $ki = ''){
    if($ki !== '') $ki .= '-';
    $rv = array();
    foreach($p as $k => $v){
        if(is_array($v))
            $rv = array_merge($rv, array_flatten($v, $ki.$k));
        else
            $rv[$ki . $k] = $v;
    }
    return $rv;
}

The flattened dataset, helped us to do rendering in less than half the iterations, and the application response was more better after using this.

Categories: PHP, Tips Tags:
  1. No comments yet.
  1. No trackbacks yet.

sixty seven + = seventy four