PHP判断json格式是否正确的实现代码

废话不多说了,直接给大家贴代码了,具体代码如下所示:

<?php
$GLOBALS['count'] = 0;
//校验data或者content的json格式是否有错误
function data($value) {
  if (isset($value['data'])) {
    $value['data'] = json_decode($value['data'], true);
  } else if (isset($value['content'])) {
    $value['content'] = json_decode($value['content'], true);
  } else {
    die('必须要有content或者data字段');
  }
  $error = json_last_error();
  if (!empty($error)) {
    echo "<pre>";
    print_r($value);
    echo "</pre>";
  }
  return $value;
}
//校验静态资源是否存在;
function my_filter($value) {
  $needle = ['.jpg', '.jpeg', '.png', '.avi', '.mp4', '.wav', '.gif', '.mp3'];
  $root = 'D:/phpStudy/WWW/levelData/';
  foreach ($needle as $k => $v) {
    $aa = strpos($value, $v);
    if ($aa) {
      $file = $root . $value;
      if (!file_exists($file)) {
        $GLOBALS['count']++;
        return $value;
      }
    }
  }
}
//获取多维数组里面某一列的下标,并重新组成一维数组
function searchMultiArray(array $array, $search, $mode = 'key') {
  $res = array();
  foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $key => $value) {
    if ($search === ${${"mode"}}) {
      if ($mode == 'key') {
        $res[] = $value;
      } else {
        $res[] = $key;
      }
    }
  }
  return $res;
}
function my_filter_answer($value) {
  $needle = [',', '、', ' ', '.', ',,', ',,'];
  foreach ($needle as $k => $v) {
    $aa = strpos($value, $v);
    if ($aa) {
      return 1;
    }
  }
}
//将汉字,特殊字符原样变成json数据
function ch_json_encode($data) {
  $ret = ch_urlencode($data);
  $ret = json_encode($ret);
  return '\'' . addslashes(urldecode($ret)) . '\'';
}
//汉字,特殊字符变可读懂的字符串主程序
function ch_urlencode($data) {
  if (is_array($data) || is_object($data)) {
    foreach ($data as $k => $v) {
      if (is_scalar($v)) {
        if (is_array($data)) {
          $data[$k] = urlencode($v);
        } else if (is_object($data)) {
          $data->$k = urlencode($v);
        }
      } else if (is_array($data)) {
        $data[$k] = ch_urlencode($v); // 递归调用该函数
      } else if (is_object($data)) {
        $data->$k = ch_urlencode($v);
      }
    }
  }
  return $data;
}

总结

php

相关推荐