Convert a multidimensional array to a string with labels and values …. for visual testing

function array_to_pipe($array, $delimeter = '|', $parents = array(), $recursive = false) {
    $result = '';

    foreach ($array as $key => $value) {
        $group = $parents;
        array_push($group, $key);

        // check if value is an array
        if (is_array($value)) {
            if ($merge = array_to_pipe($value, $delimeter, $group, true)) {
                $result = $result . $merge;
            }
            continue;
        }

        // check if parent is defined
        if (!empty($parents)) {
            $result = $result . PHP_EOL . implode($delimeter, $group) . $delimeter . $value;
            continue;
        }

        $result = $result . PHP_EOL . $key . $delimeter . $value;
    }

    // somehow the function outputs a new line at the beginning, we fix that
    // by removing the first new line character
    if (!$recursive) {
        $result = substr($result, 1);
    }

    return $result;
}
echo '<pre>'.array_to_pipe($your_array).'</pre>';

Revisions

Tags: , ,

No comments yet.

Leave a Reply