Put multiple arrays in one large associative array

天大地大妈咪最大 提交于 2020-01-17 04:25:07

问题


I am creating a set of arrays with the following loop:

$assessmentArr = explode("&", $assessmentData);

foreach($assessmentArr as $data) {
    $fullArr = explode("_", $data);

    // Break down to only archetype and value
    $resultArr = explode("=", $fullArr[2]);

    //print_r($resultArr);
}

Which produces the following results:

Array
(
    [0] => community-support
    [1] => 24
)
Array
(
    [0] => money-rewards
    [1] => 30
)
Array
(
    [0] => status-stability
    [1] => 15
)
Array
(
    [0] => personal-professional-development
    [1] => 32
)
Array
(
    [0] => community-support
    [1] => 9
)
Array
(
    [0] => money-rewards
    [1] => 12
)
Array
(
    [0] => status-stability
    [1] => 16
)
Array
(
    [0] => personal-professional-development
    [1] => 29
)

I need to combine these into one array, and where the [0] value matches, I need to add the [1] value together.

So I would like the final output to be something like:

Array
(
    [community-support] => 33
    [money-rewards] => 42
    [status-stability] => 31
    [personal-professional-development] => 61
)

I found this question: How to merge two arrays by summing the merged values which will assist me in merging and adding the values together, but I'm not sure how to go about it when the arrays aren't assigned to a variable. Is what I am trying to do possible or am I going about this the wrong way?


回答1:


Don't make it complicated, just check if the results array already has an element with that key and if not initialize it otherwise add it. E.g.

(Add this code in your loop):

if(!isset($result[$resultArr[0]]))
    $result[$resultArr[0]] = $resultArr[1];
else
    $result[$resultArr[0]] += $resultArr[1];

Then you have your desired array:

print_r($result);



回答2:


You could do it like this

$assessmentArr = explode("&", $assessmentData);
$finalArr = array();
foreach($assessmentArr as $data) {
    $fullArr = explode("_", $data);

    // Break down to only archetype and value
    $resultArr = explode("=", $fullArr[2]);
    if(array_key_exists($resultArr[1], $finalArr)){
        $finalArr[$resultArr[0]] += $resultArr[1];
    }else{
        $finalArr[$resultArr[0]] = $resultArr[1];
    }
}

First check, if the key already exists in the array, if so you add the value to the value in the final array. Otherwise you add the new index to the final array, with the value from resultArr as inital value.

... way too slow :/



来源:https://stackoverflow.com/questions/30629340/put-multiple-arrays-in-one-large-associative-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!