You are here

function _search_autocomplete_encode_formatted in Search Autocomplete 7.3

Same name and namespace in other branches
  1. 7.4 search_autocomplete.view_autocomplete.inc \_search_autocomplete_encode_formatted()

Encodes JSON in a pretty-printed fashion.

Deprecated

The $option parameter in PHP 5.4.0 json_encode() deprecates this function.

See also

_search_autocomplete_json_encode

1 call to _search_autocomplete_encode_formatted()
views-search-autocomplete-style.tpl.php in views/theme/views-search-autocomplete-style.tpl.php

File

./search_autocomplete.view_autocomplete.inc, line 274
Search Autocomplete Enables autocomplete functionality on search fields.

Code

function _search_autocomplete_encode_formatted($v, $depth = 0) {
  $base_indent = '  ';
  $eol = '<br />';
  $indent = str_repeat($base_indent, $depth);

  // This is based on the drupal_to_js() function.
  switch (gettype($v)) {
    case 'boolean':

      // Lowercase is necessary!
      return $v ? 'true' : 'false';
    case 'integer':
    case 'double':
      return $v;
    case 'resource':
    case 'string':
      $search = array(
        '"',
        chr(92),
        chr(8),
        chr(12),
        chr(13) . chr(10),
        chr(10),
        chr(13),
        chr(9),
      );
      $replace = array(
        '\\"',
        '\\',
        '\\b',
        '\\f',
        '\\n',
        '\\n',
        '\\r',
        '\\t',
      );
      $output = str_replace($search, $replace, $v);

      /* *
            $output = str_replace(array("\r", "\n", "<", ">", "&"),
                                 array('\r', '\n', '\x3c', '\x3e', '\x26'),
                                 addslashes($output));
      /* */
      return '"' . check_plain($output) . '"';
    case 'array':

      // Arrays in JSON can't be associative.  If the array is empty or if it
      // has sequential whole number keys starting with 0, it's not associative
      // so we can go ahead and convert it as an array.
      if (empty($v) || array_keys($v) === range(0, sizeof($v) - 1)) {
        $output = array();
        foreach ($v as $val) {
          $output[] = $indent . $base_indent . _search_autocomplete_encode_formatted($val, $depth + 1);
        }
        return '[' . (!empty($output) ? $eol . implode(',' . $eol, $output) . $eol . $indent : '') . ']';
      }

    // Otherwise, fall through to convert the array as an object.
    case 'object':
      $output = array();
      foreach ($v as $key => $val) {
        $output[] = $indent . $base_indent . _search_autocomplete_encode_formatted(strval($key)) . ' : ' . _search_autocomplete_encode_formatted($val, $depth + 1);
      }
      return '{' . (!empty($output) ? $eol . implode(',' . $eol, $output) . $eol . $indent : '') . '}';
    default:
      return 'null';
  }
}