0

I have one big array which has a load of similar values but I want to put all the arrays with the same value into another array. For example, I have this array.

    array(4) {
      [0]=>
      array(8) {
       ["symbol"]=>
        string(3) "aaaa"
        ["name"]=>
        string(7) "aaaa"
        ["buy_price"]=>
        string(14) "100.0000000000"
        ["current_worth"]=>
        string(14) "100.2500000000"
      }
      [3]=>
      array(8) {
       ["symbol"]=>
        string(3) "aaa"
        ["name"]=>
        string(7) "aaaaa"
        ["buy_price"]=>
        string(14) "100.0000000000"
        ["current_worth"]=>
        string(14) "100.2500000000"
      }
      [2]=>
      array(8) {
       ["symbol"]=>
        string(3) "xxx"
        ["name"]=>
        string(7) "xxxxx"
        ["buy_price"]=>
        string(14) "100.0000000000"
        ["current_worth"]=>
        string(14) "100.2500000000"
      }
   }

I want to be able run this array through a foreach loop and then output the array results together that all have the same name. Like too

  • Name aaa -- Name aaa [0] -- Name aaa [1]

  • Name xxx -- Name xxx [0]

I am struggling how to do the logic.

2

1 Answer 1

2

If I understand correctly, you need some reducing. Assuming that $origin_array contain what you need to transform:

$result = array_reduce($origin_array, function ($carry, $item) {
    $name = $item['name'];
    $carry[$name][] = $item;
    return $carry;
}, []);

This code will make 2-dimensional array where elements grouped by name field of origin array.

Explanation

The best explanation will be to write analogical foreach loop:

$my_reduce = function ($carry, $item) { // callback, 2-nd param
    $name = $item['name'];
    $carry[$name][] = $item;
    return $carry;
};

$result = []; // initial value, 3 param

foreach($origin_array as $item) {
    $result = $my_reduce($result, $item);
}

This is roughly speaking what happens under the hood of array_reduce function.

Sign up to request clarification or add additional context in comments.

2 Comments

That is exactly what I needed! Are you able to just give a little description on what is happening in the code so I can understand better how it works :)
I tryed =) After all documentation of used function should be the best explanation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.