Answer the question
In order to leave comments, you need to log in
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 )
$new_arr_863 = array([0] => 863|20 [1] => 863|50);
$new_arr_822 = array([0] => 822|100 [1] => 822|100);
Answer the question
In order to leave comments, you need to log in
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);
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)
$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 questionAsk a Question
731 491 924 answers to any question