php数据分拆 php 分割数组

php如何将文本域的内容拆分为数组,逐行写入数据库

PHP 中的fgets() 函数可以实现

创新互联公司服务电话:18980820575,为您提供成都网站建设网页设计及定制高端网站建设服务,创新互联公司网页制作领域十余年,包括纯水机等多个领域拥有丰富的网站运维经验,选择创新互联公司,为企业保驾护航。

fgets() 函数从文件指针中读取一行。

fgets(file,length)

参数说明

file 必需。规定要读取的文件。

length 可选。规定要读取的字节数。默认是 1024 字节。

详细说明

从 file 指向的文件中读取一行并返回长度最多为 length - 1 字节的字符串。碰到换行符(包括在返回值中)、EOF 或者已经读取了 length - 1 字节后停止(要看先碰到那一种情况)。如果没有指定 length,则默认为 1K,或者说 1024 字节。

若失败,则返回 false。

注释:length 参数从 PHP 4.2.0 起成为可选项,如果忽略,则行的长度被假定为 1024 字节。从 PHP 4.3 开始,忽略掉 length 将继续从流中读取数据直到行结束。如果文件中的大多数行都大于 8 KB,则在脚本中指定最大行的长度在利用资源上更为有效。

从 PHP 4.3 开始本函数可以安全用于二进制文件。早期的版本则不行。

如果碰到 PHP 在读取文件时不能识别 Macintosh 文件的行结束符,可以激活 auto_detect_line_endings 运行时配置选项。

例如:

test.txt 文本内容如下:

Hello, this is a test file.

There are three lines here.

This is the last line.

?php

//读取一行

$file = fopen("test.txt","r");

echo fgets($file);

fclose($file);

?

输出:

Hello, this is a test file.

?php

//循环读取每一行

$file = fopen("test.txt","r");

while(! feof($file)) {

echo $str = fgets($file). "br /";

//这里可以逐行的写入数据库中

//mysql_query("insert into table(id,contents) values(NULL,'".$str."')");

}

fclose($file);

?

输出:

Hello, this is a test file.

There are three lines here.

This is the last line.

PHP根据二维数组元素数量拆分成若干个小数组?

php数组分组可以使用函数array_chunk,按照给定的规则进行遍历,如果数组的num值大于8,就整除8,获取整除的数据,然后按照整除数进行分组分块即可。

关于php拆分多维数组

数据如果来自文件的话,很好操作,下边给你示例不是来自文件的数据

?php

if($_POST){

$arr=explode("\n",$_POST["test"]);

$result=array();

foreach($arr as $data){ //这里用循环拆分

trim($data) $result[]=explode(" ",$data); //首先要检查$data是否为空

}

print_r($result);

}

?

form action="a.php" method="post"

textarea name="test" style="width:500px;height:200px;"/textarea

input type="submit" value="提交" /

/form

PHP拆分一个四位数如:4579通过程序实现个位 十位、百位、千位的拆分?

方法1:

$num=4579;

$str=(string)$num;

echo "千位".$str[0]." 百位".$str[1]." 十位".$str[2]." 个位".$str[3];

方法2:

$num=4579;

$n1=floor($num/1000);

$n2=$num/100%10;

$n3=$num/10%10;

$n4=$num%10;

echo "千位".$n1." 百位".$n2." 十位".$n3." 个位".$n4;

php如何把一组数组拆分为两部分分别存入数据库中?

?php$data = array("4,0,9#1_1", "4,5,5#1_1","4,5,1#1_1", "7,2,4#1_1", "4,4,3#1_1", "8,8,0#2_1","2,2,9#2_1","0,0,6#2_1", "0,0,7#2_1","3,3,8#2_1" );$result1 = array();

$result2 = array();

foreach($data as $key=$value)

{

$str1 = '#1_1';

$str2 = '#2_1'; if(strpos($value,$str1))

{

$tmp = str_replace($str1,'',$value);

$result1[] = $tmp;

}

else if(strpos($value,$str2))

{

$tmp = str_replace($str2,'',$value);

$result2[] = $tmp;

}

}

print_r($result1);

print_r($result2);

?

结果:Array ( [0] = 4,0,9 [1] = 4,5,5 [2] = 4,5,1 [3] = 7,2,4 [4] = 4,4,3 ) Array ( [0] = 8,8,0 [1] = 2,2,9 [2] = 0,0,6 [3] = 0,0,7 [4] = 3,3,8 )楼上大哥的是对的~~


文章标题:php数据分拆 php 分割数组
本文路径:http://pwwzsj.com/article/hgdggd.html