欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

thinkphp5框架實(shí)現(xiàn)數(shù)據(jù)庫讀取的數(shù)據(jù)轉(zhuǎn)換成json格式示例

 更新時(shí)間:2019年10月10日 10:41:21   作者:yangliwei.top:88  
這篇文章主要介紹了thinkphp5框架實(shí)現(xiàn)數(shù)據(jù)庫讀取的數(shù)據(jù)轉(zhuǎn)換成json格式,涉及thinkPHP5數(shù)據(jù)庫讀取數(shù)據(jù)與json格式轉(zhuǎn)換相關(guān)操作技巧,需要的朋友可以參考下

本文實(shí)例講述了thinkphp5框架實(shí)現(xiàn)數(shù)據(jù)庫讀取的數(shù)據(jù)轉(zhuǎn)換成json格式。分享給大家供大家參考,具體如下:

首先從數(shù)據(jù)庫讀數(shù)據(jù),然后調(diào)用list_to_tree方法,再調(diào)用findchild方法,最后輸出

$category = DB::name('Category');
$category_list = $category->select();
$data=$this->list_to_tree($category_list,'category_id','category_parent_id','children'); //調(diào)用下面的方法
$data=$this->findChild($data);
header('Content-Type:application/json; charset=utf-8');
exit(json_encode($data,JSON_UNESCAPED_UNICODE));
// return $this->fetch('index');
$this->ajaxReturn($data, 'JSON');

下面是兩個(gè)方法:

  function findChild($arr){
    static $tree=array();
    foreach ($arr as $key=>$val){
        $tree[]=$val;
        if (isset($val['_child'])){
          $this->findChild($val['_child']);
        }
      }
  return $tree;
  }
  /**
   * 把返回的數(shù)據(jù)集轉(zhuǎn)換成Tree
   * @access public
   * @param array $list 要轉(zhuǎn)換的數(shù)據(jù)集
   * @param string $pid parent標(biāo)記字段
   * @param string $level level標(biāo)記字段
   * @return array
   */
  function list_to_tree($list, $pk='id',$pid = 'pid',$child = '_child',$root=0) {
    // 創(chuàng)建Tree
    $tree = array();
    if(is_array($list)) {
    // 創(chuàng)建基于主鍵的數(shù)組引用
    $refer = array();
    foreach ($list as $key => $data) {
      $refer[$data[$pk]] =& $list[$key];
    }
    foreach ($list as $key => $data) {
      // 判斷是否存在parent
      $parentId = $data[$pid];
      if ($root == $parentId) {
      $tree[] =& $list[$key];
      }else{
      if (isset($refer[$parentId])) {
        $parent =& $refer[$parentId];
        $parent[$child][] =& $list[$key];
      }
      }
    }
    }
    return $tree;
  }

轉(zhuǎn)換之前的數(shù)據(jù),直接從數(shù)據(jù)庫讀取,不能使用:

轉(zhuǎn)換之后的數(shù)據(jù),可以被ztree樹插件直接使用的json格式:

PS:這里再為大家推薦幾款比較實(shí)用的json在線工具供大家參考使用:

在線JSON代碼檢驗(yàn)、檢驗(yàn)、美化、格式化工具:
http://tools.jb51.net/code/json

JSON在線格式化工具:
http://tools.jb51.net/code/jsonformat

在線XML/JSON互相轉(zhuǎn)換工具:
http://tools.jb51.net/code/xmljson

json代碼在線格式化/美化/壓縮/編輯/轉(zhuǎn)換工具:
http://tools.jb51.net/code/jsoncodeformat

更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP中json格式數(shù)據(jù)操作技巧匯總》、《ThinkPHP入門教程》、《thinkPHP模板操作技巧總結(jié)》、《ThinkPHP常用方法總結(jié)》、《codeigniter入門教程》、《CI(CodeIgniter)框架進(jìn)階教程》、《Zend FrameWork框架入門教程》及《PHP模板技術(shù)總結(jié)》。

希望本文所述對(duì)大家基于ThinkPHP框架的PHP程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論