Kyon147
Kyon147

Reputation: 798

Putting Array with same values into another array?

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

I am struggling how to do the logic.

Upvotes: 0

Views: 57

Answers (1)

Nikita U.
Nikita U.

Reputation: 3618

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.

Upvotes: 2

Related Questions