search
HomeBackend DevelopmentPHP Tutorial数组针对某项的求和问题

已知数组a:

array (  0 =>   array (    'stock_no' => 'SU13080800340',    'adress' => 'B',    'arr_time' => '2013-08-14 09:00:00',    'c_type' => 'P32E',    'cust_no' => '310F61VA5A',    'mount_total' => '1',    'total' => '16',    'c1_time' => '2013-08-10 15:00:00',    'packageno' => 'CVT121015001',  ),  1 =>   array (    'stock_no' => 'SU13080800340',    'adress' => 'B',    'arr_time' => '2013-08-14 09:00:00',    'c_type' => 'P32E',    'cust_no' => '310F61VA5B',    'mount_total' => '2',    'total' => '32',    'c1_time' => '2013-08-10 15:00:00',    'packageno' => 'CVT121015002',  ),  2 =>   array (    'stock_no' => 'SU13080800340',    'adress' => 'B',    'arr_time' => '2013-08-14 09:00:00',    'c_type' => 'P32E',    'cust_no' => '310F61VA5B',    'mount_total' => '2',    'total' => '32',    'c1_time' => '2013-08-10 15:00:00',    'packageno' => 'CVT121226001',  ),)


如何分别求得数组中的项cust_no对应的packageno的结果以及stock_no对应mount_total和total项求和的结果?
假设cust_no为310F61VA5A时,对应的packageno为CVT121225001。
    cust_no为310F61VA5B时,对应的packageno为CVT121225002,CVT121226001。

stock_no为SU13080800340时,求得的mount_total结果为3(1+2),total结果为48(16+32)。

如何达到这样的效果?


回复讨论(解决方案)

	$a = array (   0 =>    array (     'stock_no' => 'SU13080800340',     'adress' => 'B',     'arr_time' => '2013-08-14 09:00:00',     'c_type' => 'P32E',     'cust_no' => '310F61VA5A',     'mount_total' => '1',     'total' => '16',     'c1_time' => '2013-08-10 15:00:00',     'packageno' => 'CVT121015001',   ),   1 =>    array (     'stock_no' => 'SU13080800340',     'adress' => 'B',     'arr_time' => '2013-08-14 09:00:00',     'c_type' => 'P32E',     'cust_no' => '310F61VA5B',     'mount_total' => '2',     'total' => '32',     'c1_time' => '2013-08-10 15:00:00',     'packageno' => 'CVT121015002',   ),   2 =>    array (     'stock_no' => 'SU13080800340',     'adress' => 'B',     'arr_time' => '2013-08-14 09:00:00',     'c_type' => 'P32E',     'cust_no' => '310F61VA5B',     'mount_total' => '2',     'total' => '32',     'c1_time' => '2013-08-10 15:00:00',     'packageno' => 'CVT121226001',   ), );function foo1($cust_no,$a=array()){	foreach($a as $each){		if($each['cust_no'] == $cust_no){			$res[] = $each['packageno'];		}	}	if($res){		return implode(",",$res);	}else{		return false;	}}function foo2($stock_no,$a=array()){	foreach($a as $each){		if($each['stock_no'] == $stock_no){			$mount_total[] = $each['mount_total'];			$total[] = $each['total'];		}	}	$mount_total = array_unique($mount_total);		//去重复	$total = array_unique($total);	$res['mount_total'] = array_sum($mount_total);	$res['total'] = array_sum($total);	return $res;}var_export(foo1("310F61VA5B",$a));var_export(foo2("SU13080800340",$a));


'CVT121015002,CVT121226001'
array ( 'mount_total' => 3, 'total' => 48, ) 

$ar=array (  0 =>   array (    'stock_no' => 'SU13080800340',    'adress' => 'B',    'arr_time' => '2013-08-14 09:00:00',    'c_type' => 'P32E',    'cust_no' => '310F61VA5A',    'mount_total' => '1',    'total' => '16',    'c1_time' => '2013-08-10 15:00:00',    'packageno' => 'CVT121015001',  ),  1 =>   array (    'stock_no' => 'SU13080800340',    'adress' => 'B',    'arr_time' => '2013-08-14 09:00:00',    'c_type' => 'P32E',    'cust_no' => '310F61VA5B',    'mount_total' => '2',    'total' => '32',    'c1_time' => '2013-08-10 15:00:00',    'packageno' => 'CVT121015002',  ),  2 =>   array (    'stock_no' => 'SU13080800340',    'adress' => 'B',    'arr_time' => '2013-08-14 09:00:00',    'c_type' => 'P32E',    'cust_no' => '310F61VA5B',    'mount_total' => '2',    'total' => '32',    'c1_time' => '2013-08-10 15:00:00',    'packageno' => 'CVT121226001',  ),);foreach($ar as $v){    $a[$v['cust_no']][]=$v['packageno'];	$b[$v['stock_no']][]=$v['mount_total'];	$c[$v['stock_no']][]=$v['total'];}print_r($a);print_r($b);print_r($c);

Array
(
    [310F61VA5A] => Array
        (
            [0] => CVT121015001
        )

    [310F61VA5B] => Array
        (
            [0] => CVT121015002
            [1] => CVT121226001
        )

)
Array
(
    [SU13080800340] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 2
        )

)
Array
(
    [SU13080800340] => Array
        (
            [0] => 16
            [1] => 32
            [2] => 32
        )

)

第一个问题 循环数组 判断每一个cust_no字段的值为给定值的数组元素的packageno的值加起来 就是你要的结果.  

第二个问题 循环数组 判断每一个stock_no字段的值为给定值的数组元素的两个要求字段的值存入数组,循环结束后分别去除重复的然后相加

$a = array (  0 =>   array (    'stock_no' => 'SU13080800340',    'adress' => 'B',    'arr_time' => '2013-08-14 09:00:00',    'c_type' => 'P32E',    'cust_no' => '310F61VA5A',    'mount_total' => '1',    'total' => '16',    'c1_time' => '2013-08-10 15:00:00',    'packageno' => 'CVT121015001',  ),  1 =>   array (    'stock_no' => 'SU13080800340',    'adress' => 'B',    'arr_time' => '2013-08-14 09:00:00',    'c_type' => 'P32E',    'cust_no' => '310F61VA5B',    'mount_total' => '2',    'total' => '32',    'c1_time' => '2013-08-10 15:00:00',    'packageno' => 'CVT121015002',  ),  2 =>   array (    'stock_no' => 'SU13080800340',    'adress' => 'B',    'arr_time' => '2013-08-14 09:00:00',    'c_type' => 'P32E',    'cust_no' => '310F61VA5B',    'mount_total' => '2',    'total' => '32',    'c1_time' => '2013-08-10 15:00:00',    'packageno' => 'CVT121226001',  ),);$res = array();foreach($a as $item) {  if(! isset($res[$item['stock_no']][$item['cust_no']])) {    $res[$item['stock_no']][$item['cust_no']] = $item;  }else {    $res[$item['stock_no']][$item['cust_no']]['mount_total'] += $item['mount_total'];    $res[$item['stock_no']][$item['cust_no']]['total'] += $item['total'];    $res[$item['stock_no']][$item['cust_no']]['packageno'] .= ',' .$item['packageno'];  }}foreach($res as &$item) $item = array_values($item);print_r($res);
Array
(
    [SU13080800340] => Array
        (
            [0] => Array
                (
                    [stock_no] => SU13080800340
                    [adress] => B
                    [arr_time] => 2013-08-14 09:00:00
                    [c_type] => P32E
                    [cust_no] => 310F61VA5A
                    [mount_total] => 1
                    [total] => 16
                    [c1_time] => 2013-08-10 15:00:00
                    [packageno] => CVT121015001
                )

            [1] => Array
                (
                    [stock_no] => SU13080800340
                    [adress] => B
                    [arr_time] => 2013-08-14 09:00:00
                    [c_type] => P32E
                    [cust_no] => 310F61VA5B
                    [mount_total] => 4
                    [total] => 64
                    [c1_time] => 2013-08-10 15:00:00
                    [packageno] => CVT121015002,CVT121226001
                )

        )

)

[code=php]
Array
(
    [310F61VA5A] => Array
        (
            [0] => CVT121015001
        )

    [310F61VA5B] => Array
        (
            [0] => CVT121015002
            [1] => CVT121226001
        )

)
Array
(
    [SU13080800340] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 2
        )

)
Array
(
    [SU13080800340] => Array
        (
            [0] => 16
            [1] => 32
            [2] => 32
        )

)

第一项OK,但是mount_total和total的求和结果不对,我要的是stock_no为SU13080800340时,求得的mount_total结果为3(1+2),total结果为48(16+32)。

$res = array();foreach($a as $item) {  if(! isset($res[$item['stock_no']][$item['cust_no']])) {    $res[$item['stock_no']][$item['cust_no']] = $item;  }else {    $res[$item['stock_no']][$item['cust_no']]['mount_total'] += $item['mount_total'];    $res[$item['stock_no']][$item['cust_no']]['total'] += $item['total'];    $res[$item['stock_no']][$item['cust_no']]['packageno'] .= ',' .$item['packageno'];  }}foreach($res as &$item) $item = array_values($item);print_r($res);


我想要得到的stockno的求和结果是mount_total为3(2+1),total结果为48(16+32)。

楼主这种问题  应该算是比较基础的  我有点好奇为什么会纠结于
Array
        (
            [0] => 16
            [1] => 32
            [2] => 32
        )
这种数组的加和? 你的需求应该是去了重复求和....  一个PHP函数的事情...

你的数组中三个stock_no的值不是一样的吗,都为 SU13080800340 吧,难道我眼花了?

那是你的数据给错了
    'cust_no' => '310F61VA5A',
    'mount_total' => '1',
    'total' => '16',

    'cust_no' => '310F61VA5B',
    'mount_total' => '2',
    'total' => '32',

    'cust_no' => '310F61VA5B',
    'mount_total' => '2',
    'total' => '32',

那是你的数据给错了
    'cust_no' => '310F61VA5A',
    'mount_total' => '1',
    'total' => '16',

    'cust_no' => '310F61VA5B',
    'mount_total' => '2',
    'total' => '32',

    'cust_no' => '310F61VA5B',
    'mount_total' => '2',
    'total' => '32',
那我再想想。

你的数组中三个stock_no的值不是一样的吗,都为 SU13080800340 吧,难道我眼花了?
那怎么去重复求和呢?

那是你的数据给错了
    'cust_no' => '310F61VA5A',
    'mount_total' => '1',
    'total' => '16',

    'cust_no' => '310F61VA5B',
    'mount_total' => '2',
    'total' => '32',

    'cust_no' => '310F61VA5B',
    'mount_total' => '2',
    'total' => '32',
如果是去重复求和呢?


那是你的数据给错了
    'cust_no' => '310F61VA5A',
    'mount_total' => '1',
    'total' => '16',

    'cust_no' => '310F61VA5B',
    'mount_total' => '2',
    'total' => '32',

    'cust_no' => '310F61VA5B',
    'mount_total' => '2',
    'total' => '32',
如果是去重复求和呢?

去重复求和  抬头看看一楼....

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 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

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor