php结合mysql查询无限下级树输出

 更新时间:2016年11月25日 15:34  点击:1552
php结合mysql查询无限下级树输出的例子其实就是无限分类了这里给各位整理了几个php无限分类的例子,希望对各位有所帮助。

树输出


function get_array($user_id,$top=0){
global $mysql,$_G;
   $sql = "select  user_id as name from `{spreads_users}`   where p1.spreads_userid='{$user_id}'";
$rows= $mysql->db_fetch_arrays($sql);
    if($top==1){
    $arr[0]['name']=$user_id;
    $arr[0]['children']=array();
    }
    $top=$top+1;
foreach ($rows as $key=>$value)
 {
            $r = get_array($value['name']); //调用函数,传入参数,继续查询下级   
            $arr[0]['children'][$key]['name']= $value['username']; //组合数组
            if(is_array($r)){
            $arr[0]['children'][$key]['children']= $r[0]['children'];
            }
          
           $i++;
        }
       
       
        return $arr;
    }
$list = get_array("1000",1); //调用函数  1000是顶级ID
echo 'var data='.json_encode($list);
 
这个是输出 Array 然后转让为 json 本教程由岑溪网站开发提供! 实测

例子

表结构:id字段为分类标识,name字段为分类名,father_id字段为所属父分类的id,path字段为分类路径(储存该分类祖先的集合),isdir判断是否是目录(1为是,0为否)。

显示函数:

代码如下://$count为分类等级 
sort_list($str,$fatherid,$count) 

$rs = $this->sql->re_datas("select * from sort where father_id = fatherid"); 
$num = $this->sql->sql_numrows(); 
$i=0; 
$n = 1; 
while(isset($rs[$i])) 

$name = ""; 
for($n = 1 ; $n < $count ; $n ) 

$name.="│ "; 

if($i 1==$num) 

$name.="└─".$rs[$i][name]; 

else 

$name.="├─".$rs[$i][name]; 

if($rs[$i][isdir]) 

$str.="<span style='color:#CCCCCC'>".$name."</span>"; 

else 

$str.=$name"; 

$temp = $count 1; 
$str = $this->sort_list($str,$rs[$i][id],$temp); 
$i ; 

return $str; 
}

其中$this->sql对象为sql操作类对象,re_datas()函数返回查到的数组,sql_numrows()函数返回查询到的数目

调用方法:$sort_list = sort_list($sort_list,0,1);

例子

表:category
id   int   主键,自增
name    varchar    分类名称
pid    int    父类id,默认0

顶级分类的 pid 默认就是0了。当我们想取出某个分类的子分类树的时候,基本思路就是递归,当然,出于效率问题不建议每次递归都查询数据库,通常的做法是先讲所有分类取出来,保存到PHP数组里,再进行处理,最后还可以将结果缓存起来以提高下次请求的效率。

先来构建一个原始数组,这个直接从数据库中拉出来就行:

$categories = array(
    array('id'=>1,'name'=>'电脑','pid'=>0),
    array('id'=>2,'name'=>'手机','pid'=>0),
    array('id'=>3,'name'=>'笔记本','pid'=>1),
    array('id'=>4,'name'=>'台式机','pid'=>1),
    array('id'=>5,'name'=>'智能机','pid'=>2),
    array('id'=>6,'name'=>'功能机','pid'=>2),
    array('id'=>7,'name'=>'超级本','pid'=>3),
    array('id'=>8,'name'=>'游戏本','pid'=>3),
);目标是将它转化为下面这种结构

电脑
—笔记本
——-超级本
——-游戏本
—台式机
手机
—智能机
—功能机

用数组来表示的话,可以增加一个 children 键来存储它的子分类:

array(
    //1对应id,方便直接读取
    1 => array(
        'id'=>1,
        'name'=>'电脑',
        'pid'=>0,
        children=>array(
            &array(
                'id'=>3,
                'name'=>'笔记本',
                'pid'=>1,
                'children'=>array(
                    //此处省略
                )
            ),
            &array(
                'id'=>4,
                'name'=>'台式机',
                'pid'=>1,
                'children'=>array(
                    //此处省略
                )
            ),
        )
    ),
    //其他分类省略
)处理过程:

$tree = array();
//第一步,将分类id作为数组key,并创建children单元
foreach($categories as $category){
    $tree[$category['id']] = $category;
    $tree[$category['id']]['children'] = array();
}
//第二部,利用引用,将每个分类添加到父类children数组中,这样一次遍历即可形成树形结构。
foreach ($tree as $k=>$item) {
    if ($item['pid'] != 0) {
        $tree[$item['pid']]['children'][] = &$tree[$k];
    }
}
print_r($tree);打印结果如下:

Array
(
    [1] => Array
        (
            [id] => 1
            [name] => 电脑
            [pid] => 0
            [children] => Array
                (
                    [0] => Array
                        (
                            [id] => 3
                            [name] => 笔记本
                            [pid] => 1
                            [children] => Array
                                (
                                    [0] => Array
                                        (
                                            [id] => 7
                                            [name] => 超级本
                                            [pid] => 3
                                            [children] => Array
                                                (
                                                )
                                        )
                                    [1] => Array
                                        (
                                            [id] => 8
                                            [name] => 游戏本
                                            [pid] => 3
                                            [children] => Array
                                                (
                                                )
                                        )
                                )
                        )
                    [1] => Array
                        (
                            [id] => 4
                            [name] => 台式机
                            [pid] => 1
                            [children] => Array
                                (
                                )
                        )
                )
        )
    [2] => Array
        (
            [id] => 2
            [name] => 手机
            [pid] => 0
            [children] => Array
                (
                    [0] => Array
                        (
                            [id] => 5
                            [name] => 智能机
                            [pid] => 2
                            [children] => Array
                                (
                                )
                        )
                    [1] => Array
                        (
                            [id] => 6
                            [name] => 功能机
                            [pid] => 2
                            [children] => Array
                                (
                                )
                        )
                )
        )
    [3] => Array
        (
            [id] => 3
            [name] => 笔记本
            [pid] => 1
            [children] => Array
                (
                    [0] => Array
                        (
                            [id] => 7
                            [name] => 超级本
                            [pid] => 3
                            [children] => Array
                                (
                                )
                        )
                    [1] => Array
                        (
                            [id] => 8
                            [name] => 游戏本
                            [pid] => 3
                            [children] => Array
                                (
                                )
                        )
                )
        )
    [4] => Array
        (
            [id] => 4
            [name] => 台式机
            [pid] => 1
            [children] => Array
                (
                )
        )
    [5] => Array
        (
            [id] => 5
            [name] => 智能机
            [pid] => 2
            [children] => Array
                (
                )
        )
    [6] => Array
        (
            [id] => 6
            [name] => 功能机
            [pid] => 2
            [children] => Array
                (
                )
        )
    [7] => Array
        (
            [id] => 7
            [name] => 超级本
            [pid] => 3
            [children] => Array
                (
                )
        )
    [8] => Array
        (
            [id] => 8
            [name] => 游戏本
            [pid] => 3
            [children] => Array
                (
                )
        )
)优点:关系清楚,修改上下级关系简单。

缺点:使用PHP处理,如果分类数量庞大,效率也会降低。

imagettftext是一个图形处理函数了,如果在使用imagettftext函数时碰到Call to undefined function imagettftext()的话就是函数组件没有打开了,所以我们只需要简单的配置即可。

在一个新环境中装Tipask v2.5的时候发现后台验证码无法显示。出错的函数是imagettftext(),由于index.php使用了error_reporting(0)将错误隐去,导致这次莫名的错误,去掉,错误立马出现:

Fatal error: Call to undefined function imagettftext()
现在我们就明确了,出现错误的原因是PHP编译时没有加上FreeType。

解决办法

首先编译安装FreeType,以2.4.0为例:

wget http://download.savannah.gnu.org/releases/freetype/freetype-2.4.0.tar.bz2
tar -jxf freetype-2.4.0.tar.bz2
cd reetype-2.4.0
# 安装到/usr/local/freetype
./configure –prefix=/usr/local/freetype
make && make install
下面我们重新编译PHP,加上参数–with-freetype-dir=/usr/local/freetype

./configure –with-freetype-dir=/usr/local/freetype
编译完成重启php

kill -USR2 `cat /usr/local/php/var/run/php-fpm.pid`
再GD库中找到FreeType Support说明安装成功!

需要注意的是,如果服务器freetype的版本是1.*,那么你可能需要改变编译参数为–with-ttf[=DIR],以下转自ChinaUnix论坛:

字库 配置开关
FreeType 1.x 要激活 FreeType 1.x 的支持,加上 –with-ttf[=DIR]。
FreeType 2 要激活 FreeType 2 的支持,加上 –with-freetype-dir=DIR。
T1lib 要激活 T1lib(Type 1 字体),加上 –with-t1lib[=DIR]。
本地 TrueType 字符串函数 要激活本地 TrueType 字符串函数的支持,加上 –enable-gd-native-ttf。

有许多的站长会把自己的图片利用php输出来了这样的话对于用户来讲没有什么区别对于搜索引擎来讲有一些区别了,如果我们没有更新但输入的还是不是304的话搜索引擎会认为图片更新了,为了解决这个问题我们来看看如何处理吧。

什么是304 状态

如果客户端发送了一个带条件的GET 请求且该请求已被允许,而文档的内容(自上次访问以来或者根据请求的条件)并没有改变,则服务器应当返回这个304状态码。简单的表达就是:客户端已经执行了GET,但文件未变化。

php 动态输出图片为什么要输入304

客户端是怎么知道这些内容没有更新的呢?其实这并不是客户端的事情,而是你服务器的事情,大家都知道服务器可以设置缓存机制,这个功能是为了提高网站的访问速度,当你发出一个GET请求的时候服务器会从缓存中调用你要访问的内容,这个时候服务器就可以判断这个页面是不是更新过了,如果没有更新过那么他会给你返回一个304状态码。


有时候需要是用php动态生成图片,比如 多个比例的缩略图

但是是用php生成的图片的header 头部状态都是200,不能被缓存,这显然也不太合适。

可以如何通过缓存PHP生成的图像。此功能只检查头,看看图像是否是最新的,并发送304代码,如果是这样,那么浏览器将使用缓存的版本,而不是下载新的。否则新的图像输出到浏览。

php 动态输出图片 http header 304 代码


<?php
// return the browser request header
// use built in apache ftn when PHP built as module,
// or query $_SERVER when cgi
function getRequestHeaders()
{
    if (function_exists("apache_request_headers"))
    {
        if($headers = apache_request_headers())
        {
            return $headers;
        }
    }
 
    $headers = array();
    // Grab the IF_MODIFIED_SINCE header
    if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']))
    {
        $headers['If-Modified-Since'] = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
    }
    return $headers;
}
 
// Return the requested graphic file to the browser
// or a 304 code to use the cached browser copy
function displayGraphicFile ($graphicFileName, $fileType='jpeg')
{
    $fileModTime = filemtime($graphicFileName);
    // Getting headers sent by the client.
    $headers = getRequestHeaders();
    // Checking if the client is validating his cache and if it is current.
    if (isset($headers['If-Modified-Since']) &&
        (strtotime($headers['If-Modified-Since']) == $fileModTime))
    {
        // Client's cache IS current, so we just respond '304 Not Modified'.
        header('Last-Modified: '.gmdate('D, d M Y H:i:s', $fileModTime).
                ' GMT', true, 304);
    }
    else
    {
        // Image not cached or cache outdated, we respond '200 OK' and output the image.
        header('Last-Modified: '.gmdate('D, d M Y H:i:s', $fileModTime).
                ' GMT', true, 200);
        header('Content-type: image/'.$fileType);
        header('Content-transfer-encoding: binary');
        header('Content-length: '.filesize($graphicFileName));
        readfile($graphicFileName);
    }
}
 
//example usage
displayGraphicFile("./images/image.png");
 
?>

如果你碰到在系统中生成文件数据太长了然后自动截断了,那么会是什么原因呢,这个小编碰到过post数据丢失所导致的问题了,今天我们来看看吧。


在使用xml来导出excel时,发现小数量(1k以下)时能正常导出excel,但将导出数量调大(几K)时,发现导出的excel数据不全。

(在我本地是好的,在线上服务器跑就有问题。。。)
检查导出的xml数据,发现内容被截断了,有时连xml标签都不全。

php-xml-excel

首先怀疑是输出的内容字节过长,超出了环境配置的上限。检查了output_buffering和nginx的fastcgi_buffer相关设置,都没有问题。和我本地的值一样,修改后也没有影响。

之后就Google了下,发现有出现类似情况的,是权限问题,于是去检查nginx的错误日志error.log。
发现在导出操作时有如下错误记录:

2016/02/04 09:47:53 [crit] 19027#0: *967389 mkdir() "/tmp/fastcgi_temp/xxx" failed (13: Permission denied) while reading upstream, client:xxx.xxx.xx.xxx

看来确实是权限有问题,导出时nginx要创建一个/tmp/fastcgi_temp/xxx的目录,但失败了。
跑去/tmp下检查,发现根本没有fastcgi_temp目录!!于是手动新建目录/tmp/fastcgi_temp/,并设置所有者www、权限744。

重新运行导出,xml被截断的问题已解决。

PHPExcel导出大量数据超时及内存错误解决方法

PHPExcel是一个很强大的处理Excel的PHP开源类,但是很大的一个问题就是它占用内存太大,从1.7.3开始,它支持设置cell的缓存方式,但是推荐使用目前稳定的版本1.7.6,因为之前的版本都会不同程度的存在bug,以下是其官方文档:

PHPExcel1.7.6官方文档 写道

PHPExcel uses an average of about 1k/cell in your worksheets, so large workbooks can quickly use up  available memory. Cell caching provides a mechanism that allows PHPExcel to maintain the cell objects in a smaller size of memory, on disk, or in APC, memcache or Wincache, rather than in PHP memory. This allows you to reduce the memory usage for large workbooks, although at a cost of speed to access cell data.

PHPExcel 平均下来使用1k/单元格的内存,因此大的文档会导致内存消耗的也很快。单元格缓存机制能够允许PHPExcel将内存中的小的单元格对象缓存在磁盘或者 APC,memcache或者Wincache中,尽管会在读取数据上消耗一些时间,但是能够帮助你降低内存的消耗。

PHPExcel1.76.官方文档 写道

By default, PHPExcel still holds all cell objects in memory, but you can specify alternatives. To enable cell caching, you must call the PHPExcel_Settings::setCacheStorageMethod() method, passing in the caching method  that you wish to use.

默认情况下,PHPExcel依然将单元格对象保存在内存中,但是你可以自定义。你可以使用PHPExcel_Settings::setCacheStorageMethod()方法,将缓存方式作为参数传递给这个方法来设置缓存的方式。

Php代码:

$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_in_memory;

PHPExcel_Settings::setCacheStorageMethod($cacheMethod);

PHPExcel1.7.6官方文档 写道

setCacheStorageMethod() will return a boolean true on success, false on failure (for example if trying to    cache to APC when APC is not enabled).

setCacheStorageMethod()方法会返回一个BOOL型变量用于表示是否成功设置(比如,如果APC不能使用的时候,你设置使用APC缓存,将会返回false)

PHPExcel1.7.6官方文档 写道

A separate cache is maintained for each individual worksheet, and is automatically created when the    worksheet is instantiated based on the caching method and settings that you have configured. You cannot    change the configuration settings once you have started to read a workbook, or have created your first    worksheet.

每一个worksheet都会有一个独立的缓存,当一个worksheet实例化时,就会根据设置或配置的缓存方式来自动创建。一旦你开始读取一个文件或者你已经创建了第一个worksheet,就不能在改变缓存的方式了。

PHPExcel1.7.6官方文档 写道

Currently, the following caching methods are available.

目前,有以下几种缓存方式可以使用:

Php代码:

PHPExcel_CachedObjectStorageFactory::cache_in_memory;

PHPExcel1.7.6官方文档 写道

The default. If you don’t initialise any caching method, then this is the method that PHPExcel will use. Cell    objects are maintained in PHP memory as at present.

默认情况下,如果你不初始化任何缓存方式,PHPExcel将使用内存缓存的方式。

===============================================

Php代码:

PHPExcel_CachedObjectStorageFactory::cache_in_memory_serialized;

PHPExcle1.7.6官方文档 写道

Using this caching method, cells are held in PHP memory as an array of serialized objects, which reduces the    memory footprint with minimal performance overhead.

使用这种缓存方式,单元格会以序列化的方式保存在内存中,这是降低内存使用率性能比较高的一种方案。

===============================================

Php代码:

PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;

PHPExcel1.7.6官方文档 写道

Like cache_in_memory_serialized, this method holds cells in PHP memory as an array of serialized objects,   but- gzipped to reduce the memory usage still further, although access to read or write a cell is slightly slower. 

与序列化的方式类似,这种方法在序列化之后,又进行gzip压缩之后再放入内存中,这回跟进一步降低内存的使用,但是读取和写入时会有一些慢。

===========================================================

Php代码:

PHPExcel_CachedObjectStorageFactory::cache_to_discISAM;

PHPExcel1.7.6官方文档 写道

When using cache_to_discISAM all cells are held in a temporary disk file, with only an index to their location   in that file maintained in PHP memory. This is slower than any of the cache_in_memory methods, but significantly       reduces the memory footprint.The temporary disk file is automatically deleted when your script terminates.          

当使用cache_to_discISAM这种方式时,所有的单元格将会保存在一个临时的磁盘文件中,只把他们的在文件中的位置保存在PHP的内存中,这会比任何一种缓存在内存中的方式都慢,但是能显著的降低内存的使用。临时磁盘文件在脚本运行结束是会自动删除。

===========================================================

Php代码:

PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;

PHPExcel1.7.6官方文档 写道

Like cache_to_discISAM, when using cache_to_phpTemp all cells are held in the php://temp I/O stream, with  only an index to their location maintained in PHP memory. In PHP, the php://memory wrapper stores data in the  memory: php://temp behaves similarly, but uses a temporary file for storing the data when a certain memory   limit is reached. The default is 1 MB, but you can change this when initialising cache_to_phpTemp.

类 似cache_to_discISAM这种方式,使用cache_to_phpTemp时,所有的单元格会还存在php://temp I/O流中,只把 他们的位置保存在PHP的内存中。PHP的php://memory包裹器将数据保存在内存中,php://temp的行为类似,但是当存储的数据大小超 过内存限制时,会将数据保存在临时文件中,默认的大小是1MB,但是你可以在初始化时修改它:

Php代码:

$cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_phpTemp;

$cacheSettings = array( ’ memoryCacheSize ’  => ’8MB’  );

PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);

PHPExcel1.7.6官方文档 写道

The php://temp file is automatically deleted when your script terminates.

php://temp文件在脚本结束是会自动删除。

===========================================================

Php代码:

PHPExcel_CachedObjectStorageFactory::cache_to_apc;

PHPExcle1.7.6官方文档 写道

When using cache_to_apc, cell objects are maintained in APC with only an index maintained in PHP memory   to identify that the cell exists. By default, an APC cache timeout of 600 seconds is used, which should be enough  for most applications: although it is possible to change this when initialising cache_to_APC.

当使用cach_to_apc时,单元格保存在APC中,只在内存中保存索引。APC缓存默认超时时间时600秒,对绝大多数应用是足够了,当然你也可以在初始化时进行修改:

Php代码:

 

$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_APC;

$cacheSettings = array( ’cacheTime’  => 600   );

PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);

PHPExcel1.7.6官方文档 写道

When your script terminates all entries will be cleared from APC, regardless of the cacheTime value, so it   cannot be used for persistent storage using this mechanism.

当脚本运行结束时,所有的数据都会从APC中清楚(忽略缓存时间),不能使用此机制作为持久缓存。

===========================================================

Php代码:

 

PHPExcel_CachedObjectStorageFactory::cache_to_memcache

PHPExcel1.7.6官方文档 写道

When using cache_to_memcache, cell objects are maintained in memcache with only an index maintained in  PHP memory to identify that the cell exists.

By default, PHPExcel looks for a memcache server on localhost at port 11211. It also sets a memcache  timeout limit of 600 seconds. If you are running memcache on a different server or port, then you can change   these defaults when you initialise cache_to_memcache:

使 用cache_to_memory时,单元格对象保存在memcache中,只在内存中保存索引。默认情况下,PHPExcel会在localhost和 端口11211寻找memcache服务,超时时间600秒,如果你在其他服务器或其他端口运行memcache服务,可以在初始化时进行修改:

Php代码:

$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_memcache;

$cacheSettings = array( ’memcacheServer’  => ’localhost’,

‘memcachePort’    => 11211,

‘cacheTime’       => 600

);

PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);

从初始化设置的形式上看,MS还不支持多台memcache服务器轮询的方式,比较遗憾。

PHPExcel1.7.6官方文档 写道

When your script terminates all entries will be cleared from memcache, regardless of the cacheTime value, so   it cannot be used for persistent storage using this mechanism.

当脚本结束时,所有的数据都会从memcache清空(忽略缓存时间),不能使用该机制进行持久存储。

===========================================================

Php代码:

PHPExcel_CachedObjectStorageFactory::cache_to_wincache;

PHPExcel1.7.6官方文档 写道

When using cache_to_wincache, cell objects are maintained in Wincache with only an index maintained in   PHP memory to identify that the cell exists. By default, a Wincache cache timeout of 600 seconds is used, which   should be enough for most applications: although it is possible to change this when initialising cache_to_wincache.

使用cache_towincache方式,单元格对象会保存在Wincache中,只在内存中保存索引,默认情况下Wincache过期时间为600秒,对绝大多数应用是足够了,当然也可以在初始化时修改:

Php代码:

$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_wincache;

$cacheSettings = array( ’cacheTime’  => 600 );

PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);

PHPExcel官方文档1.7.6 写道

When your script terminates all entries will be cleared from Wincache, regardless of the cacheTime value,  so  it cannot be used for persistent storage using this mechanism.

PHPExcel还是比较强大的,最大的问题就是内存占用的问题,PHPExcel啥时候能出一个轻量级的版本,不需要那么多花哨的功能,只需要导出最普通的数据的版本就好了!

有序的数组打印或排序对于php来讲非常的简单了这里整理了几个不同语言的做法的实现代码,具体的我们一起来看这篇php中有序的数组打印或排序的例子吧。


最近有个面试题挺火的——把俩个有序的数组打印或排序。刚看到这个题的时候也有点蒙,最优的算法肯定要用到有序的特性。

思考了一会发现也不是很难,假如数组是正序排列的,可以同时遍历俩个数组,将小的值进行排序,最后会遍历完一个数组,留下一个非空数组,而且剩下的值肯定大于等于已经排好序的最大值。

PHP代码之

<?php
    function sort_arr($a,$b) {
        $temp = array();
        while ($a&&$b) {
            if($a['0']<$b['0']) {
                $temp[] = array_shift($a);
            } else {
                $temp[] = array_shift($b);
            }
        }
        if(!empty($a)) { $temp = array_merge($temp, $a); }
        if(!empty($b)) { $temp = array_merge($temp, $b); }
        return $temp;
    }
    $a = array(1,2,3,4,5,6);
    $b = array(2,3,4,10,10,10,10);
    sort_arr($a, $b);
?>
 

Python 代码之

def fib(a,b):
    len_a = len(a)
    c = []
    while len(a) and len(b):
        if a[0] > b[0]:
            c.append(b.pop(0))
        else:
            c.append(a.pop(0))
    
    if len(a):
        c = c+a 
    
    if len(b):
        c = c+b
 
    i=0
    while i<len(c):
        print(c[i])
        i = i+1    
 
 
a = [1,2,3,4,5]
b = [2,3,4,5,6,7,8,9]
 
fib(a,b)

C代码之


#include &amp;lt;stdio.h&amp;gt;;
int *sort(int a[], int b[], int a_len, int b_len) {
    int *temp = malloc(a_len+b_len);
 
    int i=0; //标注a数组
    int j=0; //标注b数组
    int m=0; //标注新数组
    
    while (i&amp;lt;a_len&amp;amp;&amp;amp;j&amp;lt;b_len) { //重新排序 if(a[i]&amp;lt;b[j]) {
            temp[m++] = b[j++];
        } else {
            temp[m++] = a[i++];
        }
    }
    
    //将剩余的数字放在新数组后面(剩余的肯定是前面的数字大)
    if(i&amp;lt;a_len) {
        for (; i&amp;lt;a_len; i++) {
            temp[m++] = a[i];
        }
    }
    if(j&amp;lt;b_len) {
        for (; j&amp;lt;b_len; j++) {
            temp[m++] = b[j];
        }
    }
    
    return temp;
}
 
int main(int argc, const char * argv[]) {
    int a[4] = {2,3,11,89};
    int b[6] = {4,6,9,10,22,55};
    
    int a_len = sizeof(a) / sizeof(a[0]);
    int b_len = sizeof(b) / sizeof(b[0]);
    
    int *c = sort(a, b, a_len, b_len);
    
    int y = 0;
    for (; y&amp;lt;a_len+b_len; y++) {
        printf("%d ", c[y]);
    }
    
    return 0;
}

GO代码之


package main
 
import "fmt"
 
func main() {
    var a = [5]int{1, 2, 3, 4, 5}
    var b = [8]int{4, 5, 6, 7, 89, 100, 111, 112}
    var len_a = len(a)
    var len_b = len(b)
    var c = make([]int, len_a+len_b)
 
    var j = 0 //标注a数组
    var k = 0 //标注b数组
    var h = 0 //标注新数组
 
        
    for j &amp;lt; len_a &amp;amp;&amp;amp; k &amp;lt; len_b {
        if a[j] &amp;gt; b[k] {
            c[h] = b[k]
            h++
            k++
        } else {
            c[h] = a[j]
            h++
            j++
        }
    }
 
    if j &amp;lt; len_a {
        for i := j; i &amp;lt; len_a; i++ {
            c[h] = a[i]
            h++
        }
    }
 
    if k &amp;lt; len_b {
        for i := k; i &amp;lt; len_b; i++ {
            c[h] = b[i]
            h++
        }
    }
 
    Print(c, "c")
 
}
 
/**
 * [Print array]
 * @param {[type]} o    []int  [array]
 * @param {[type]} name string [array name]
 */
func Print(o []int, name string) {
    fmt.Printf("%s: ", name)
 
    for _, v := range o {
        fmt.Printf("%d ", v)
    }
 
    fmt.Printf("\n")
}

[!--infotagslink--]

相关文章

  • Mybatis Plus select 实现只查询部分字段

    这篇文章主要介绍了Mybatis Plus select 实现只查询部分字段的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-01
  • MySQL性能监控软件Nagios的安装及配置教程

    这篇文章主要介绍了MySQL性能监控软件Nagios的安装及配置教程,这里以CentOS操作系统为环境进行演示,需要的朋友可以参考下...2015-12-14
  • 详解Mysql中的JSON系列操作函数

    新版 Mysql 中加入了对 JSON Document 的支持,可以创建 JSON 类型的字段,并有一套函数支持对JSON的查询、修改等操作,下面就实际体验一下...2016-08-23
  • MyBatisPlus-QueryWrapper多条件查询及修改方式

    这篇文章主要介绍了MyBatisPlus-QueryWrapper多条件查询及修改方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2022-06-27
  • vue Treeselect下拉树只能选择第N级元素实现代码

    这篇文章主要介绍了vue Treeselect下拉树只能选择第N级元素实现代码,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-09-01
  • 深入研究mysql中的varchar和limit(容易被忽略的知识)

    为什么标题要起这个名字呢?commen sence指的是那些大家都应该知道的事情,但往往大家又会会略这些东西,或者对这些东西一知半解,今天我总结下自己在mysql中遇到的一些commen sense类型的问题。 ...2015-03-15
  • Oracle使用like查询时对下划线的处理方法

    这篇文章主要介绍了Oracle使用like查询时对下划线的处理方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-03-16
  • MySQL 字符串拆分操作(含分隔符的字符串截取)

    这篇文章主要介绍了MySQL 字符串拆分操作(含分隔符的字符串截取),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-02-22
  • 解决mybatis-plus 查询耗时慢的问题

    这篇文章主要介绍了解决mybatis-plus 查询耗时慢的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-07-04
  • mysql的3种分表方案

    一、先说一下为什么要分表:当一张的数据达到几百万时,你查询一次所花的时间会变多,如果有联合查询的话,有可能会死在那儿了。分表的目的就在于此,减小数据库的负担,缩短查询时间。根据个人经验,mysql执行一个sql的过程如下:1...2014-05-31
  • Python绘制的爱心树与表白代码(完整代码)

    这篇文章主要介绍了Python绘制的爱心树与表白代码,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-04-06
  • Windows服务器MySQL中文乱码的解决方法

    我们自己鼓捣mysql时,总免不了会遇到这个问题:插入中文字符出现乱码,虽然这是运维先给配好的环境,但是在自己机子上玩的时候咧,总得知道个一二吧,不然以后如何优雅的吹牛B。...2015-03-15
  • 用VirtualBox构建MySQL测试环境

    宿主机使用网线的时候,客户机在Bridged Adapter模式下,使用Atheros AR8131 PCI-E Gigabit Ethernet Controller上网没问题。 宿主机使用无线的时候,客户机在Bridged Adapter模式下,使用可选项里唯一一个WIFI选项,Microsoft Virtual Wifi Miniport Adapter也无法上网,故弃之。...2013-09-19
  • Centos5.5中安装Mysql5.5过程分享

    这几天在centos下装mysql,这里记录一下安装的过程,方便以后查阅Mysql5.5.37安装需要cmake,5.6版本开始都需要cmake来编译,5.5以后的版本应该也要装这个。安装cmake复制代码 代码如下: [root@local ~]# wget http://www.cm...2015-03-15
  • 忘记MYSQL密码的6种常用解决方法总结

    首先要声明一点,大部分情况下,修改MySQL密码是需要有mysql里的root权限的...2013-09-11
  • MySQL数据库备份还原方法

    MySQL命令行导出数据库: 1,进入MySQL目录下的bin文件夹:cd MySQL中到bin文件夹的目录 如我输入的命令行:cd C:/Program Files/MySQL/MySQL Server 4.1/bin (或者直接将windows的环境变量path中添加该目录) ...2013-09-26
  • MySQL中在查询结果集中得到记录行号的方法

    如果需要在查询语句返回的列中包含一列表示该条记录在整个结果集中的行号, ISO SQL:2003 标准提出的方法是提供 ROW_NUMBER() / RANK() 函数。 Oracle 中可以使用标准方法(8i版本以上),也可以使用非标准的 ROWNUM ; MS SQL...2015-03-15
  • Mysql命令大全(详细篇)

    一、连接Mysql格式: mysql -h主机地址 -u用户名 -p用户密码1、连接到本机上的MYSQL。首先打开DOS窗口,然后进入目录mysql/bin,再键入命令mysql -u root -p,回车后提示你输密码.注意用户名前可以有空格也可以没有空格,但是密...2015-11-08
  • node.js如何操作MySQL数据库

    这篇文章主要介绍了node.js如何操作MySQL数据库,帮助大家更好的进行web开发,感兴趣的朋友可以了解下...2020-10-29
  • Node实现搜索框进行模糊查询

    这篇文章主要为大家详细介绍了Node实现搜索框进行模糊查询,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-06-28