programmierfrage.com
Ask a question    Sign Up Sign In
  • Train typing speed
  • About/Contact
  • Privacy Policy
  1. Home
  2. PHP group and sum multidimensional array

787 votes
2 answers

PHP group and sum multidimensional array

Get the solution ↓↓↓
Closed. This question needs details or clarity. It is not currently accepting answers.

Undefined asked
2021-09-2
Write your answer



613
votes

Answer

Solution:

This is a way to get the desired result. I tried to be creative (I think this is not the most direct way and maybe not the best way).

The last element in each inner array in your input's array ($arr) is a string (without associative key), I don't know you made a mistake when put single quotes or this was your intention. I take them like key and value pairs.

Code:

I broke the original array (and the result array) in two arrays, one with the arrays to look for and the other with the amount's arrays. If I find the look for array in the result array, I sum both amounts. Finally I merge the two result arrays.

<?php

//Input data:
$array = [
        ['type' => 'x', 'color' => 'red', 'amount' => 100],
        ['type' => 'x', 'color' => 'red', 'amount' => 100],
        ['type' => 'y', 'color' => 'blue', 'amount' => 50]
    ];

$arrayResultSearch = array();
$arrayResultAmount = array();

foreach($array as $elemnt) {
    list($arrayTypeColor, $arrayAmount) = array_chunk($elemnt, 2, true);

    if(! in_array($arrayTypeColor, $arrayResultSearch)) {
        $arrayResultSearch[] = $arrayTypeColor;
        $arrayResultAmount[] = $arrayAmount;
    } else {
        $key = key($arrayAmount);
        $value = current($arrayAmount);

        $arrayResultAmount[array_search($arrayTypeColor, $arrayResultSearch)][$key] += $value;
    }
}

$arrrayResult = array_map(function($a, $b) { return array_merge($a, $b); }, $arrayResultSearch, $arrayResultAmount);

?>

Result ($arrrayResult):

array ( 0 => array ( 'type' => 'x', 'color' => 'red', 'amount' => 200, ), 1 => array ( 'type' => 'y', 'color' => 'blue', 'amount' => 50, ), )
Write your answer




296
votes

Answer

Solution:

I solved it like this:

$arr = [
        ['type' => 'x', 'color' => 'red', 'amount' => 100],
        ['type' => 'x', 'color' => 'red', 'amount' => 100],
        ['type' => 'y', 'color' => 'blue', 'amount' => 50]
    ];
    // Create an array with unique types
    $types = [];
    foreach ($arr as $a) {
       if(!in_array($a['type'], $types))
           $types[] = $a['type'];
    }
    // Loop through that array and sum amount of all equal types
    #$x = [];
    $i = 0;
    foreach ($types as $type) {
        $x[$i]['amount'] = 0;
        foreach ($arr as $a) {
            if($type == $a['type']){ // we have a matching type (x or y)
                $x[$i]['type'] = $a['type'];
                $x[$i]['color'] = $a['color'];
                $x[$i]['amount'] += $a['amount'];
            }
        }
        $i += 1;
    }

dump:

array (
  0 => 
  array (
    'amount' => 200,
    'type' => 'x',
    'color' => 'red',
  ),
  1 => 
  array (
    'amount' => 50,
    'type' => 'y',
    'color' => 'blue',
  ),
)
Write your answer




Share solution ↓

Additional Information:

Date the issue was resolved:
2021-09-2
Link To Source
Link To Answer People are also looking for solutions of the problem: a non well formed numeric value encountered

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Similar questions

Find the answer in similar questions on our website.

424 laravel - How can I merge array in multidimensional array in PHP
671 php - Solve PHP4 to PHP5 ugrade error
832 php - Use of undefined constant message - assumed 'message'
985 php - How to restructure the array so is possible to store each answer and question_id in the answers table?
777 How to convert PHP array into Yaml?
241 php - Yii2 dropdown optgroup label
540 arrays - Php if elseif loop is not working fine
688 PHP 5.4 code update - Creating default object from empty value warnings in foreach and objects array
261 php json array data in javascript
318 sql - Select result in grouped row using fetch and while in PHP

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.






About the technologies asked in this question

PHP

PHP (from the English Hypertext Preprocessor - hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites. The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/



Welcome to programmierfrage.com

programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration.

Get answers to specific questions

Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.

Help Others Solve Their Issues

Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.

Yacht Magazine



Latest questions:

203 xml - php FOR not work

665 MySQL Search Limit using PHP

651 php - Solve PHP4 to PHP5 ugrade error

994 php - logic behind displaying time values with seconds and minutes range

584 php - Making a 'quiz' - how do I show previous answer?

382 php - When should I return true/false to AJAX and when should I echo "true"/"false"

24 zend framework - PHP: How do you get the book weight and category/genre using the Amazon API?

612 php - Database design: implementing several types of the same entity

664 php - Doctrine: extra where on relation (many-to-many)

530 database - Getting the db name or url used from models in php activerecord?

Users questions:

NEW

mysql

NEW

Warning: Undefined array key "program" in E:\xampp\htdocs\pi\alumni.php on line 27 Warning: Undefined array key "enter_course" in E:\xampp\htdocs\pi\alumni.php on line 31 Warning: Undefined array key "enter_address" in E:\xampp\htdocs\pi\alumni.php on line 32

NEW

Rename existing images with keyword in WordPress PHP

NEW

codeigniter

NEW

Class "web_profiler.controller.profiler" does not exist after upgrading symfony 3.4 to 4.4 version




PHP x 410847
Laravel x 36785
Yii x 3846
CodeIgniter x 9997
Symfony x 7793
CakePHP x 3085
Zend Framework x 1235
Phalcon x 300
FuelPHP x 47
Slim x 570
JavaScript x 36883
React x 550
Angular x 1121
Vue.js x 181
JQuery x 11108
Backbone.js x 21
Node.js x 463
Ember.js x 10
Meteor x 7
Polymer x 20
Aurelia x 1
MySQL x 39074
CSS x 2497
Bootstrap x 1603
Foundation x 84
UIkit x 4
Semantic UI x 2
Bulma x 2
Animate.css x 1
HTML x 20978




© 2021-2023 Programming problem solving site for beginners and advanced. Answers to questions related to coding.

E-mail: [email protected]

This site uses cookies. We use them to improve the performance of our website and your interaction with it. Confirm your consent by clicking OK


OK