I am working on a project where I have to sum score for some tags. The idea is to make the array even values key and odd values as values I did search on google but I fail to create a structure like below. I need the array structure like below this way I can easily sum the values with the same key.
$array = array("22" => 3, "27" => 2, "30" => 1, so on...) from the below array.
[0] => 22
[1] => 3
[2] => 27
[3] => 2
[4] => 30
[5] => 1
[6] => 22
[7] => 3
[8] => 25
[9] => 2
[10] => 28
[11] => 1
The code I am using to map the array with key-value pair according to the above logic.
$rank = $_POST['ranking_details'];
$rinfo = explode('_', $rank);
$result = array_map(function($v){
return [$v[0] => $v[1]];
}, $rinfo);
print_r($result);
Output:
Array
(
[0] => Array
(
[2] => 2
)
[1] => Array
(
[3] =>
)
[2] => Array
(
[2] => 7
)
[3] => Array
(
[2] =>
)
[4] => Array
(
[3] => 0
)
CodePudding user response:
Is this what you're looking for?
Code:
$arr = array(22, 3, 27, 2, 30, 1, 22, 3);
for ($i = 0; $i < count($arr); $i = 2) {
$dic[$arr[$i]] = $arr[$i 1];
}
print_r($dic);
Output:
Array
(
[22] => 3
[27] => 2
[30] => 1
)
CodePudding user response:
you can use this
$result = [];
for($i = 0; $i < count($rinfo); $i = 2) {
if(true === isset($rinfo[$i 1])){
$result[$rinfo[$i]] = $rinfo[$i 1];
}
}
example:
$rinfo = [1,2,3,4,5,6,7,8];
//print_r($result);
Array
(
[1] => 2
[3] => 4
[5] => 6
[7] => 8
)