V
V
VladBokov2020-05-27 21:35:48
PHP
VladBokov, 2020-05-27 21:35:48

What is the logic behind creating new arrays from an existing one by iterating in a loop?

Greetings! Orient please logically, even I'm at an impasse.
I have an array :

Array ( [0] => 863|20 [1] => 863|50 [2] => 822|100 [3] => 822|100 )


In foreach, I use explode to get two values ​​from a string by splitting it after the | .
How to make it so that in the iterations of the array iteration, I could create new $new_arr[] arrays that would be filled only with those values ​​from the iteration, if the zero index of the explode array was equal to that in the first array.
For example. I have two rows in an array with values. which start at 863. I need new arrays to be created in foreach, but sorted by 863.
$new_arr_863 = array([0] => 863|20 [1] => 863|50);
$new_arr_822 = array([0] => 822|100 [1] => 822|100);


All this is needed in order to further obtain the sum of the values ​​of the second substring from explode in each array. So it turns out:
Array 863 will have a value with a sum of 70
Array 822 = 200.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Edward, 2020-05-27
@VladBokov

VladBokov

$arr = [
    '863|20',
    '863|50',
    '822|100',
    '822|100'
];

$out = [];

foreach ($arr as $item) {
    [$k, $v] = explode('|', $item);
    $out[$k][] = $v;
}

var_dump($out);

Result
array (size=2)
  863 => 
    array (size=2)
      0 => string '20' (length=2)
      1 => string '50' (length=2)
  822 => 
    array (size=2)
      0 => string '100' (length=3)
      1 => string '100' (length=3)

UPD :
Supplemented the answer with summation
$arr = [
    '863|20',
    '863|50',
    '822|100',
    '822|100'
];

$out = [];

foreach ($arr as $item) {
    [$k, $v] = explode('|', $item);
    $out[$k] = ($out[$k] ?? 0) + $v;
}

var_dump($out);
/* 
array (size=2)
  863 => int 70
  822 => int 200
*/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question