search
HomeBackend DevelopmentPHP Tutorial多行数据组合数组问题~~,真心不会组合了,求教导!



类似上面的表单,还没加js,不一定多少行,我要做的是每行一条数据写入数据库。这个数组我就不会组合了
我表单里是如下设置的:

<table width="100%" border="0" cellspacing="0" cellpadding="0">  <tr>    <td>    品名:<input name="pinming[]" type="text" value="">    型号:<input name="xinghao[]" type="text" value="">    规格:<input name="guige[]" type="text" value="">    数量:<input name="shuliang[]" type="text" value="">    单价:<input name="danjia[]" type="text" value="">    总价:<input name="zongjia[]" type="text" value="">    </td>  </tr>  <tr>    <td>    品名:<input name="pinming[]" type="text" value="">    型号:<input name="xinghao[]" type="text" value="">    规格:<input name="guige[]" type="text" value="">    数量:<input name="shuliang[]" type="text" value="">    单价:<input name="danjia[]" type="text" value="">    总价:<input name="zongjia[]" type="text" value="">    </td>  </tr>  </table>


获取到的数组是这样的
array  'pinming' =>     array      0 => string '123' (length=3)      1 => string '123' (length=3)  'xinghao' =>     array      0 => string '123' (length=3)      1 => string '123' (length=3)  'guige' =>     array      0 => string '123' (length=3)      1 => string '123' (length=3)  'shuliang' =>     array      0 => string '123' (length=3)      1 => string '123' (length=3)  'danjia' =>     array      0 => string '123' (length=3)      1 => string '123' (length=3)  'zongjia' =>     array      0 => string '12312' (length=5)      1 => string '123' (length=3)


我怎么将上面的数组变成下面的样子

array(    //第一条    array(        'pinming' => 'xxx'        'guige' => 'xxx'        //....其他字段    )    //第二条    array(        'pingming' => 'xxx'        'guige' => 'xxx'        //其他字段    )    //第N条    array())


回复讨论(解决方案)

不就一个行列交换么?

class squareArray{	public function swapRowCol($inArr)	{		$mit = new MultipleIterator(MultipleIterator::MIT_KEYS_ASSOC);		foreach($inArr as $key => $value) { $temArr = new ArrayIterator($value); $mit->attachIterator($temArr, $key); }		$arr = array();		foreach($mit as $item) array_push($arr,$item);		if (isset($inArr[0])) $arr = array_combine(array_keys($inArr[0]),$arr);		return $arr;	}	public function swapRowColWithKey($inArr)	{		foreach($inArr as $k1=>$v1) foreach($v1 as $k2=>$v2) $arr[$k2][$k1] = $v2;		return $arr;	}...

本来你的输入网页就应该设计成一行(一个td)用一组变量名,那不就简单了

foreach($_POST as $name=>$item) {  if(is_array($item)) {    foreach($item as $key=>$value) {      $res[$kek][$name] = $value;    }  }}
$res 就是你要的结果

$fields=array('pinming','guige','xinghao','shuliang','danjia','zongjia');$data=array();foreach($_POST['pinming'] as $key=>$vo){    foreach($fields as $item){        $data[$key][$item]=$_POST[$key][$item];    }}//$data is the result

foreach($_POST as $name=>$item) {  if(is_array($item)) {    foreach($item as $key=>$value) {      $res[$kek][$name] = $value;    }  }}
$res 就是你要的结果

版主你好,加了js以后可能会出现用户点击增加一行后什么也不填写就提交,这样会写一条空记录,怎么判断抛弃空记录的数组

先完成行列转换,然后删去全空的项目

foreach($res as $i=>$item) {  if(trim(join('', $item)) == '') unset($res[$i]);}

这种提交没有必要搞这么复杂

只要你确定1点就可以简单化,就是哪一项是必填项,也就是说不能为空的

这里我假设品名不能为空,那么程序之需要这样就可以

foreach($pinming as $key=>$val) {   $uparr=array();  if(trim($val)!='') {    $uparr['pinming']=$val;    $uparr['xinghao']=$pinming[$key];    $uparr['guige']=$guige[$key];    $uparr['shuliang']=$shuliang[$key];    $uparr['danjia']=$danjia[$key];    $uparr['zongjia']=$zongjia[$key];   //这里加插入数据库语句  }}


foreach($_POST as $name=>$item) {  if(is_array($item)) {    foreach($item as $key=>$value) {      $res[$kek][$name] = $value;    }  }}
$res 就是你要的结果

版主你好,加了js以后可能会出现用户点击增加一行后什么也不填写就提交,这样会写一条空记录,怎么判断抛弃空记录的数组
没有必要要做组合的,你目的不外乎就是逐条插入数据库,我在7#的代码就可以满足了



foreach($_POST as $name=>$item) {  if(is_array($item)) {    foreach($item as $key=>$value) {      $res[$kek][$name] = $value;    }  }}
$res 就是你要的结果

版主你好,加了js以后可能会出现用户点击增加一行后什么也不填写就提交,这样会写一条空记录,怎么判断抛弃空记录的数组
没有必要要做组合的,你目的不外乎就是逐条插入数据库,我在7#的代码就可以满足了

我用的是Thinkphp的关联模型 HAS_MANY 一次性就能提交过去 所以我要传一个这样的数组进去!




foreach($_POST as $name=>$item) {  if(is_array($item)) {    foreach($item as $key=>$value) {      $res[$kek][$name] = $value;    }  }}
$res 就是你要的结果

版主你好,加了js以后可能会出现用户点击增加一行后什么也不填写就提交,这样会写一条空记录,怎么判断抛弃空记录的数组
没有必要要做组合的,你目的不外乎就是逐条插入数据库,我在7#的代码就可以满足了

我用的是Thinkphp的关联模型 HAS_MANY 一次性就能提交过去 所以我要传一个这样的数组进去!

那我用我的方法一样可以组合,插入数据库的地方变成组合新数组形式就可以

也就是

$newarr=array();foreach($pinming as $key=>$val) {   $uparr=array();  if(trim($val)!='') {    $uparr['pinming']=$val;    $uparr['xinghao']=$pinming[$key];    $uparr['guige']=$guige[$key];    $uparr['shuliang']=$shuliang[$key];    $uparr['danjia']=$danjia[$key];    $uparr['zongjia']=$zongjia[$key];    $newarr[]=$uparr;   }}


哎,要懂得变通,而不是死思维

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

What is the full form of PHP?What is the full form of PHP?Apr 28, 2025 pm 04:58 PM

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

How does PHP handle form data?How does PHP handle form data?Apr 28, 2025 pm 04:57 PM

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

What is the difference between PHP and ASP.NET?What is the difference between PHP and ASP.NET?Apr 28, 2025 pm 04:56 PM

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

Is PHP a case-sensitive language?Is PHP a case-sensitive language?Apr 28, 2025 pm 04:55 PM

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),