search
HomeBackend DevelopmentPHP Tutorialphp中数组中某个键值为空的时候,不加入到数组。

	$data = array();			if (!empty($_POST['field_id'])) {				foreach ($_POST['field_id'] as $k => $v) {					$data[] = array(						'field_id' => $v, 						'choice' => isset($_POST['choice'][$k]) ? $_POST['choice'][$k] : '', 						'uid' => $_POST['uid'],						'game_id' => $_POST['game_id'],						'server_id' => $_POST['server_id']					);  				}   			}  

这是我循环格式化的地方,下面是输出的数组数据
Array(    [0] => Array        (            [field_id] => 1            [choice] => 0            [uid] => 110000110            [game_id] => 2            [server_id] => 2        )    [1] => Array        (            [field_id] => 2            [choice] => 0            [uid] => 110000110            [game_id] => 2            [server_id] => 2        )    [2] => Array        (            [field_id] => 3            [choice] => 1            [uid] => 110000110            [game_id] => 2            [server_id] => 2        ))


当choiece等于空的时候   [choice] =>没有值的时候不加入到data数组里面怎么实现呢?


回复讨论(解决方案)

 [1] => Array
        (
            [field_id] => 2
            [choice] => 
            [uid] => 110000110
            [game_id] => 2
            [server_id] => 2
    )
像这样的情况,0和1是有值的。

你示例的数据中并没有  [choice] => 的情况
如果有的话,是仅不要  choice 项,还是整组都不要?

你对 $_POST['choice'] 循环,不是比对 $_POST['field_id'] 循环等容易点吗?

你示例的数据中并没有  [choice] => 的情况
如果有的话,是仅不要  choice 项,还是整组都不要?

你对 $_POST['choice'] 循环,不是比对 $_POST['field_id'] 循环等容易点吗?



Array
(
    [0] => Array
        (
            [field_id] => 1
            [choice] => 0
            [uid] => 110000110
            [game_id] => 2
            [server_id] => 2
        )

    [1] => Array
        (
            [field_id] => 2
            [choice] => 
            [uid] => 110000110
            [game_id] => 2
            [server_id] => 2
        )

    [2] => Array
        (
            [field_id] => 3
            [choice] => 
            [uid] => 110000110
            [game_id] => 2
            [server_id] => 2
        )

)

大概就是这样一个效果,没有值的就不要了,显示成这样
Array
(
    [0] => Array
        (
            [field_id] => 1
            [choice] => 0
            [uid] => 110000110
            [game_id] => 2
            [server_id] => 2
        )
)
只有choice没有值的就整个数组都不要了。

$data = array();if (!empty($_POST['field_id'])) {   foreach ($_POST['choice'] as $k => $v) {      if($v == '') continue;      $data[] = array(          'field_id' => $_POST['field_id'][$k],           'choice' => $_POST['choice'][$k],           'uid' => $_POST['uid'],          'game_id' => $_POST['game_id'],          'server_id' => $_POST['server_id']      );    }   }
 

$data = array();if (!empty($_POST['field_id'])) {   foreach ($_POST['choice'] as $k => $v) {      if($v == '') continue;      $data[] = array(          'field_id' => $_POST['field_id'][$k],           'choice' => $_POST['choice'][$k],           'uid' => $_POST['uid'],          'game_id' => $_POST['game_id'],          'server_id' => $_POST['server_id']      );    }   }
 


谢谢版主,不过我下面用的批量添加的时候,如果已经选择过了的会提示失败,tp里面addall怎么判断是否已经添加过了呢
$Choice=D('Myselect');			//$choices=$Choice->addAll($data);			if($Choice->addAll($data)){				$back['status']='success';				$back['msg']='您的投注已经成功!';				$back['url']='game';				$this->back($back);			 	}else{				$back['status']='error';				$back['msg']='投注失败!别重复下注哦!';				$back['url']='game';				$this->back($back);				exit;				}			}

if($Choice->addAll($data,array(),true)){}看了下mod默认是false,改成true会一直改变数据库的值,那就没有意义了
if($Choice->addAll($data,array(),false)){}这种情况怎么判断是否已经存在数据库了呢,各位前辈有什么好的办法吗?

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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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 Article

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)