【nginx】得到IP地址

Continue Read..

nginx 

  proxy_set_header X-Real-IP $remote_addr;

  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

  proxy_set_header Host $host;

  real_ip_header    X-Forwarded-For;

  real_ip_recursive on;

 

php 

<?php

echo long2ip(_get_ip());

function _get_ip($full = false) {

        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {

            if ($full == true)

                return sprintf("%u\n", ip2long($_SERVER["HTTP_X_FORWARDED_FOR"]));

            $tmp_ips = explode(',', $_SERVER["HTTP_X_FORWARDED_FOR"]);

            $ip = array_shift($tmp_ips);

        }

        else if (isset($_SERVER["HTTP_CLIENT_IP"]))

            $ip = $_SERVER["HTTP_CLIENT_IP"];

        else if (isset($_SERVER["REMOTE_ADDR"]))

            $ip = $_SERVER["REMOTE_ADDR"];

        else if (getenv("HTTP_X_FORWARDED_FOR"))

            $ip = getenv("HTTP_X_FORWARDED_FOR");

        else if (getenv("HTTP_CLIENT_IP"))

            $ip = getenv("HTTP_CLIENT_IP");

        else if (getenv("REMOTE_ADDR"))

            $ip = getenv("REMOTE_ADDR");

        else

            $ip = "Unknown";

        return sprintf("%u\n", ip2long($ip));

    }


声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【thinkphp5】ThinkPHP5如何使用build.php

Continue Read..

进入application

php ../think build --config ..\build.php

 

 

build.php里面写需要生成的配置

 

 

return [
    // 生成应用公共文件
    '__file__' => ['common.php''config.php''database.php'],

    // 定义demo模块的自动生成 (按照实际定义的文件名生成)
    'xxx'     => [
        '__file__'   => ['common.php'],
        '__dir__'    => ['behavior''controller''model''view'],
        'controller' => ['Index''Test''UserType'],
        'model'      => ['User''UserType'],
        'view'       => ['index/index'],
    ],
    // 其他更多的模块定义
];

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【php】RabbitMQ+supervisord+php消息队列

Continue Read..
CentOS7安装RabbitMQ

由于rabbitmq是基于erlang语言开发的,所以必须先安装erlang。
安装依赖
yum -y install gcc glibc-devel make ncurses-devel openssl-devel xmlto perl wget gtk2-devel binutils-devel

erlang官网:

https://www.erlang.org/downloads

下载(会比较慢,请耐心等待)

wget http://erlang.org/download/otp_src_22.0.tar.gz

移走

mv otp_src_22.0 /usr/local/

切换目录

cd /usr/local/otp_src_22.0/
 

创建即将安装的目录

mkdir ../erlang
 

配置安装路径

./configure --prefix=/usr/local/erlang

如果遇到这个错 你就假装没看到

点击查看原图
安装

make install

 

查看一下是否安装成功

ll /usr/local/erlang/bin
 

添加环境变量

echo 'export PATH=$PATH:/usr/local/erlang/bin' >> /etc/profile
 

刷新环境变量

source /etc/profile
 

甩一条命令

erl
 
点击查看原图
瞬间进入了一个未知的世界

在里面输入halt().命令退出来(那个点号别忘记)

点击查看原图



安装RabbitMQ
rabbitmq下载地址:

https://github.com/rabbitmq/rabbitmq-server/releases/tag/v3.7.15

 

下载

wget https://github.com/rabbitmq/rabbitmq-server/releases/download/v3.7.15/rabbitmq-server-generic-unix-3.7.15.tar.xz
 

由于是tar.xz格式的所以需要用到xz,没有的话就先安装 

yum install -y xz
 

第一次解压

/bin/xz -d rabbitmq-server-generic-unix-3.7.15.tar.xz
 

第二次解压

tar -xvf rabbitmq-server-generic-unix-3.7.15.tar
 

移走

mv rabbitmq_server-3.7.15/ /usr/local/
 

改名

mv /usr/local/rabbitmq_server-3.7.15  rabbitmq
 

配置环境变量

echo 'export PATH=$PATH:/usr/local/rabbitmq/sbin' >> /etc/profile
 

刷新环境变量

source /etc/profile
 

创建配置目录

mkdir /etc/rabbitmq
 

回到顶部
启动命令
启动:

rabbitmq-server -detached
 

停止:

rabbitmqctl stop
 

状态:

rabbitmqctl status
 

防火墙之类的请自行处理(5672和15672端口),反正我是从来不开防火墙。

 

回到顶部
WEB管理
开启web插件

rabbitmq-plugins enable rabbitmq_management
 

访问:http://127.0.0.1:15672/
点击查看原图 

默认账号密码:guest guest(这个账号只允许本机访问)

 

回到顶部
用户管理
查看所有用户

rabbitmqctl list_users
 

添加一个用户

rabbitmqctl add_user admin 123456
 

配置权限

rabbitmqctl set_permissions -p "/" admin ".*" ".*" ".*"
 

查看用户权限

rabbitmqctl list_user_permissions admin
 

设置tag

rabbitmqctl set_user_tags admin administrator
 

删除用户(安全起见,删除默认用户)

rabbitmqctl delete_user guest
 

回到顶部
登陆
配置好用户之后重启一下rabbit

然后就可以用新账号进行登陆

点击查看原图

 

 

安装supervisord

yum install epel-release

yum install -y supervisor

 

#yum -y install python-setuptools zlib

easy_install supervisor

echo_supervisord_conf > /etc/supervisord.conf

 

mkdir -p /data/etc/supervisord/

mkdir -p /data2/logs/supervisord/

chmod 777 /data2/logs/supervisord/

 

修改 /etc/supervisord.conf

sed -i -e "s#logfile=/tmp/supervisord.log#logfile=/data2/logs/supervisord/supervisord.log#g" /etc/supervisord.conf

sed -i -e "s#file=/tmp/supervisor.sock#file=/var/run/supervisor.sock#g" /etc/supervisord.conf

sed -i -e "s#pidfile=/tmp/supervisord.pid#pidfile=/var/run/supervisord.pid#g" /etc/supervisord.conf

sed -i -e "s#serverurl=unix:///tmp/supervisor.sock#serverurl=unix:///var/run/supervisor.sock#g" /etc/supervisord.conf

echo "[include]" >> /etc/supervisord.conf

echo "files = /data/www/supervisord/*.ini" >> /etc/supervisord.conf

 

 

 

操作脚本:

vi /usr/lib/systemd/system/supervisord.service

 

#输入下面内容,并保存

[Unit]

Description=Supervisord

After=network.target

 

[Service]

Type=forking

PIDFile=/var/run/supervisord.pid

ExecStart=/usr/bin/supervisord -c /etc/supervisord.conf

ExecStop=/bin/kill -TERM $MAINPID

ExecReload=/bin/kill -HUP $MAINPID

Restart=always

 

[Install]

WantedBy=multi-user.target

保存

 

#修改权限

chmod +x /usr/lib/systemd/system/supervisord.service

 

systemctl enable supervisord.service

启用:systemctl start supervisord

 

#其它控制命令

systemctl stop supervisord

systemctl reload supervisord

 

查看进程列表:

systemctl status supervisord

#supervisorctl status

停止进程 mq_test_worker:

supervisorctl stop mq_test_worker:

开始进程 mq_test_worker::

supervisorctl start mq_test_worker:

 

 

启动程序如果提示:Starting supervisor: Error: Another program is already listening on a port that one of our HTTP servers is configured to use.  Shut this program down first before starting supervisord.

unlink /var/run/supervisor.sock

 

 

 

sudo chmod 777 /run

sudo chmod 777 /var/log

sudo touch /var/run/supervisor.sock

sudo chmod 777 /var/run/supervisor.sock

supervisord -c /etc/supervisord.conf

ps aux | grep supervisord

 

 

 

最后效果

supervisord -c /etc/supervisord.conf 开启supervisord服务

supervisorctl start mq_test_worker 开启需要常驻的脚本服务

执行脚本test.php

然后tail -f mq_test_worker.log 里面可以看到队列的数据

 

点击查看原图

 

 

代码附件 : msg_broker.zip

 

 参考网站

RabbitMQ:https://www.cnblogs.com/fengyumeng/p/11133924.html

supervisord(碰到的坑):

https://www.missshi.cn/api/view/blog/5aafcf405b925d681e000000

https://www.cnblogs.com/ruanraun/p/supervisor.html

https://blog.csdn.net/weixin_41762173/article/details/88901970

 

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【php】win修改php-cgi.exe启动接口

Continue Read..
1、先要运行起php的cgi,由于本人用的win7系统,所以cmd先进的c盘(之前全扔c盘这就简单了~),访问到php路径中,输入
php-cgi.exe -b 127.0.0.1:9000
注意这里的-b 127.0.0.1:9000是指定cgi的监听端口,与上文中的Nginx配置要一致,如果有其他配置不记得之前php-cgi是那个端口,可以使用php-cgi.exe -h命令来查看配置(查看-b 后面的<address:port>)。想要查看所有被监听的端口则输入netstat -na

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【php】mysql跨库回滚

Continue Read..
CREATE TABLE afu.`test2` (
  `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(50) DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
CREATE TABLE trade.`test2` (
  `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(50) DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
<?php
/**
 * Created by PhpStorm.
 * User: cuzn
 * Date: 2018/12/28
 * Time: 19:10
 */


namespace app\afu\cron\department;

use app\afu\api\model\afu\Test2Model;
use app\afu\api\model\trade\Test1Model;
use PhpOffice\PhpSpreadsheet\Exception;

require_once __DIR__ . '/../../conf/config.inc.php';

echo "exec at " . date('Y-m-d H:i:s') . "\n";


$Test1Model = Test1Model::getInstance();


function addTest2($isBack = false){
    $Test2Model = Test2Model::getInstance();
    try {
        $Test2Model->begin();
    
        $ret = $Test2Model->insert([
            'name' => 'bbbbbbb'
        ]);
        if (!$isBack) {
            $Test2Model->commit();
            return true;
        } else {
            $Test2Model->rollback();
            return false;
        }
    } catch (Exception $e) {
        $Test2Model->rollback();
        throw $e;
        //return false;
    }
}


try {
    $Test1Model->begin();
    
    $ret = $Test1Model->insert([
        'name' => 'aaaaaa'
    ]);
    $ret2 = addTest2(false);
    var_dump($ret, $ret2);
    if ($ret && $ret2) {
        $Test1Model->commit();
    }else {
        $Test1Model->rollback();
    }
} catch (Exception $e) {
    //addTest2(1);
    $Test1Model->rollback();
    throw $e;
}


声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【PHP】mysql嵌套事物

Continue Read..

公司的一个项目需要在一个函数里面的调用多个函数,但是每个函数都用到了mysql事物,按照原生的mysql事物,只有一层

也就是说 A函数包含了B函数,如果B函数事物成功,A再没有commit的时候也能提交事物,这样就不对了

 

直接上代码

 

写一个class

定义一个静态变量

//事物laravel

static private $transactions = 0;

 

public function begin() {
        ++self::$transactions;
        if (self::$transactions == 1) {
            $sql = 'BEGIN';
            $conn = $this->getMasterConn();
            
            return DBMysqli::execute($conn, $sql);
        }
	}

	/**
	 * 提交事务
	 *
	 * @return bool
	 * @throws Exception
	 */
	public function commit() {
        if (self::$transactions == 1) {
            $sql = 'COMMIT';
            $conn = $this->getMasterConn();
            
            return DBMysqli::execute($conn, $sql);
        }
        --self::$transactions;
	}

	/**
	 * 回滚事务
	 *
	 * @return bool
	 * @throws Exception
	 */
	public function rollback() {
        if (self::$transactions == 1) {
            self::$transactions = 0;
            $sql = 'ROLLBACK';
            $conn = $this->getMasterConn();
    
            return DBMysqli::execute($conn, $sql);
        } else {
            --self::$transactions;
        }
	}

参考网站 https://blog.csdn.net/hello_katty/article/details/45220825

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【PHP】php 返回数组中指定多列的方法

Continue Read..
function array_columns($input, $column_keys=null, $index_key=null){ $result = array(); $keys =isset($column_keys)? explode(',', $column_keys) : array(); if($input){ foreach($input as $k=>$v){ // 指定返回列 if($keys){ $tmp = array(); foreach($keys as $key){ $tmp[$key] = $v[$key]; } }else{ $tmp = $v; } // 指定索引列 if(isset($index_key)){ $result[$v[$index_key]] = $tmp; }else{ $result[] = $tmp; } } } return $result; }

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【php】excel导出分sheet

Continue Read..
    /**
     * 导出export 生成多个sheet
     * $data = [
     *      'sheet1'=>[
     *          'header'=>['k'=>v],
     *          'date'=>['k'=>v],
     *      ]
     *      'sheet2'=>[
     *          'header'=>['k'=>v]
     *          'data'=>['k'=>v]
     *      ]
     * ]
     * header和data 用k 关联
     * @param unknown $data
     * @param string $user
     * @param string $format
     * @param string $title
     * @return multitype:mixed
     */  
    public function multiExportSheet($data, $user = 'admin', $format = false, $title = ''){
        require_once __DIR__.'/PHPExcel.php';
        $objPHPExcel = new \PHPExcel();
        $j = 0;
        foreach ($data as $dk=>$dv){
            if($j==0){
                $objPHPExcel->setActiveSheetIndex($j); //设置第一个工作表为活动工作表
                $objPHPExcel->getActiveSheet()->setTitle($dk); //设置工作表名称
            }else{
                $msgWorkSheet = new \PHPExcel_Worksheet($objPHPExcel, $dk); //创建一个工作表
                $objPHPExcel->addSheet($msgWorkSheet); //插入工作表
                $objPHPExcel->setActiveSheetIndex($j); //切换到新创建的工作表
            }
            
            $arrHeader = $dv['header'];
            $arrBody = $dv['data'];
            $newdata = [];
            
            $i = 0;
            foreach ($arrBody as $k=>$v){
                foreach ($arrHeader as $kk=>$vv){
                    if(!empty($v[$kk])){
                        if($kk == 'idcard' || $kk == 'bank_card'){
                            $newdata[$i][$kk] = $v[$kk]."\t";
                        }else{
                            $newdata[$i][$kk] = $v[$kk];
                        }
                    }else{
                        $newdata[$i][$kk] = "";
                    }
                }
                $i++;
            }
            $hd[0] = $arrHeader;
            $arrExcelInfo = array_merge($hd, $newdata);
            $objPHPExcel->getActiveSheet()->fromArray(
                $arrExcelInfo, // 赋值的数组
                NULL, // 忽略的值,不会在excel中显示
                'A1' // 赋值的起始位置
            );
            
            unset($arrExcelInfo);
            unset($hd);
            unset($arrHeader);
            unset($arrBody);
            unset($newdata);
            $j++;
        }
        
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    
        $result=[];
        $path = 'down/'.md5($user.'down').'/';
        $rootPath = $this->mkdirPath($path);
        $date = date('YmdHis');
    
        $title = $date.rand(10000,99999);
        $outputFileName = $rootPath.$title.".xlsx";
        $objWriter->save($outputFileName);
        $result[]= str_replace(APP_PATH, '', $outputFileName);
        return $result;
    }


声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【PHP】七牛,php<=5.3版本

Continue Read..
<?php
class SDK implements ArrayAccess {

	const QINIU_UP_HOST	= 'http://up.qiniu.com';
	const QINIU_RS_HOST	= 'http://rs.qbox.me';
	const QINIU_RSF_HOST= 'http://rsf.qbox.me';
	//查看 
	//删除 
	//复制 x
	//移动 x
	//上传 
	protected $access_token ;
	protected $secret_token ;
	protected $bucket;
	protected $cache = array();
	protected $aliases = array(); //文件别名, 针对文件名比较长的文件
	//curl 
	protected $ch;
	protected $headers;
	protected $options = array();
	protected $response;
	protected $info;
	protected $errno; 
	protected $error;

	public function __construct($access_token, $secret_token, $bucket = null)
	{
		$this->access_token = $access_token;
		$this->secret_token = $secret_token;
		$this->bucket = $bucket;
	}

	//获取空间名称
	public function getBucket()
	{
		return $this->bucket;
	}

	//设置空间
	public function setBucket($bucket)
	{
		$this->bucket = $bucket;
	}

	/**
	 * 查看指定文件信息。
	 * @param  string $key  	文件名或者目录+文件名
	 * @return Array|boolean 	成功返回文件内容,否会返回false.
	 */
	public function stat($key)
	{
		list($bucket, $key) = $this->parseKey($key);
		if ( is_null($bucket) ) 
		{
			die('error');
		}
		$url = self::QINIU_RS_HOST .'/stat/' . $this->encode("$bucket:$key");
		$token = $this->accessToken($url);
		$options[CURLOPT_HTTPHEADER] = array('Authorization: QBox '. $token);
		return $this->get($url, $options);
	}

	/**
	 * 删除指定文件信息。
	 * @param  string $key  	文件名或者目录+文件名
	 * @return NULL
	 */
	public function delete($key)
	{
		list($bucket, $key) = $this->parseKey($key);
		if ( is_null($bucket) ) 
		{
			die('error');
		}
		$url = self::QINIU_RS_HOST .'/delete/' . $this->encode("$bucket:$key");

		$token = $this->accessToken($url);
		$options[CURLOPT_HTTPHEADER] = array('Authorization: QBox '. $token);
		return $this->get($url, $options);
	}

	public function upload($file, $name=null, $token = null)
	{
		if ( NULL === $token ) 
		{
			$token = $this->uploadToken($this->bucket);
		}

		if ( !file_exists($file) ) 
		{
			die('文件不存在,构建一个临时文件');
		}
		$hash = hash_file('crc32b', $file);
		$array = unpack('N', pack('H*', $hash));
		$postFields = array(
			'token' => $token,
			'file'  => '@'.$file,
			'key'   => $name,
// 			'crc32' => sprintf('%u', $array[1]),
		);

		//未指定文件名,使用七牛默认的随机文件名
		if ( NULL === $name ) 
		{
			unset($postFields['key']);
		}
		else
		{
			//设置文件名后缀。
		}
		$options = array(
			CURLOPT_POSTFIELDS => $postFields,
		);
		return $this->get(self::QINIU_UP_HOST, $options);
	}

	protected function parseKey($key)
	{
		$key = $this->getAlias($key);
		if ( isset($this->cache[$key]) ) 
		{
			return $this->cache[$key];
		}
		$segments = explode("|", $key);
		if ( count($segments) === 1 ) 
		{
			$this->cache[$key] = array($this->bucket, $segments[0]);
		}
		else
		{
			$temp = implode('|', array_slice($segments, 1));
			$this->cache[$key] = array($segments[0], $temp);
		}
		return $this->cache[$key];
	}

	public function getAlias($key)
	{
		return isset($this->aliases[$key]) ? $this->aliases[$key] : $key;
	}

	public function uploadToken($config = array())
	{
		if ( is_string($config) ) 
		{
			$scope = $config;
			$config = array();
		}
		else
		{
			$scope = $config['scope'];
		}
		$config['scope'] = $scope;
		//硬编码,需修改。
		$config['deadline'] = time() + 3600;
		foreach ( $this->activeUploadSettings($config) as $key => $value ) 
		{
			if ( $value ) 
			{
				$config[$key] = $value;
			}
		}

		//build token
		$body = json_encode($config);
		$body = $this->encode($body);
		$sign = hash_hmac('sha1', $body, $this->secret_token, true);
		return $this->access_token . ':' . $this->encode($sign) . ':' .$body;
	}

	public function uploadSettings()
	{
		return array(
			'scope','deadline','callbackUrl', 'callbackBody', 'returnUrl',
			'returnBody', 'asyncOps', 'endUser', 'exclusive', 'detectMime',
			'fsizeLimit', 'saveKey', 'persistentOps', 'persistentNotifyUrl'
		);
	}

	protected function activeUploadSettings($array)
	{
		return array_intersect_key($array, array_flip($this->uploadSettings()));
	}

	public function accessToken($url, $body = false)
	{
		$url = parse_url($url);
		$result = '';
		if (isset($url['path'])) {
			$result = $url['path'];
		}
		if (isset($url['query'])) {
			$result .= '?' . $url['query'];
		}
		$result .= "\n";
		if ($body) {
			$result .= $body;
		}
		$sign = hash_hmac('sha1', $result, $this->secret_token, true);
		return $this->access_token . ':' . $this->encode($sign);
	}

	public function get($url, $options = array())
	{
		$this->ch = curl_init();
		$this->options[CURLOPT_URL] = $url;
		$this->options = $options + $this->options;
		//临时处理逻辑
		
		return $this->execute();
	}

	protected function execute() 
	{
		if ( !$this->option(CURLOPT_RETURNTRANSFER) ) 
		{
			$this->option(CURLOPT_RETURNTRANSFER, true);
		}
		if ( !$this->option(CURLOPT_SSL_VERIFYPEER) ) 
		{
			$this->option(CURLOPT_SSL_VERIFYPEER, false);
		}
		if ( !$this->option(CURLOPT_SSL_VERIFYHOST) ) 
		{
			$this->option(CURLOPT_SSL_VERIFYHOST, false);
		}
		if ( !$this->option(CURLOPT_CUSTOMREQUEST) ) 
		{
			$this->option(CURLOPT_CUSTOMREQUEST, 'POST');
		}
		if ( $this->headers ) 
		{
			$this->option(CURLOPT_HTTPHEADER, $this->headers);
		}
		$this->setupCurlOptions();

		$this->response = curl_exec($this->ch);
		$this->info = curl_getinfo($this->ch);

		if ( $this->response === false ) 
		{
			$this->error = curl_error($this->ch);
			$this->errno = curl_errno($this->ch);
			curl_close($this->ch);
			return false;
		}
		else
		{
			curl_close($this->ch);
			//未处理http_code。
			if ( $this->info['content_type'] == 'application/json' ) 
			{
				$this->response = json_decode($this->response, true);
			}
			return $this->response;
		}
	}
	public function setupCurlOptions()
	{
		curl_setopt_array($this->ch, $this->options);
	}

	public function option($key, $value = NULL)
	{
		if ( is_null($value) ) 
		{
			return !isset($this->options[$key]) ? null: $this->options[$key];
		}
		else
		{
			$this->options[$key] = $value;
			return $this;
		}
	}

	public function alias($key, $value)
	{
		$this->alias[$key] = $value;
	}

	protected function encode($str)
	{
        $trans = array("+" => "-", "/" => "_");
        return strtr(base64_encode($str), $trans);
	}

	public function __get($key)
	{
		return $this->$key;
	}

	public function offsetExists($key)
	{
		//check response;
	}

	public function offsetGet($key)
	{
		return $this->stat($key);
	}

	public function offsetSet($key, $value) 
	{
		//move or copy
	}

	public function offsetUnset($key)
	{
		return $this->delete();
	}
}


upload($filePath,$key);
var_dump($update);die;










声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权

【PHP】无限极函数

Continue Read..

数据库

CREATE TABLE `position` (
   `position_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '岗位id',
   `position_ids` text COMMENT '所属父级ids',
   `position_name` varchar(50) NOT NULL COMMENT '岗位名称',
   `position_addtime` int(11) DEFAULT NULL COMMENT '添加时间',
   `position_uptime` int(11) DEFAULT NULL COMMENT '修改时间',
   `parent_id` int(11) DEFAULT NULL COMMENT '父级id',
   `is_delete` int(11) NOT NULL DEFAULT '0' COMMENT '是否删除',
   `role_id` int(10) DEFAULT NULL COMMENT '角色id',
   PRIMARY KEY (`position_id`)
 ) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=utf8 COMMENT='岗位表'

点击查看原图

 

 

$data = select * from position

 

$newData = [];

foreach ($data as $k=>$v){

    $newData[$v['position_id']] = $v;

}

 

foreach ($data as $k=>$v){

    if($v['parent_id'] && isset($newData[$v['parent_id']])){

        $newData[$v['parent_id']]['son'][] = &$newData[$v['position_id']];

    }

}

 

var_dump($newData);die;

 

 

 

声明:此文系舞林cuznwww.wulinlw.org)原创稿件,转载请保留版权