0

I have an array like this. Each array is having a user ID with scores populated dynamically. I want to add all the strings inside the array and have the key as userID

array(3) {
  [13702]=>
  array(2) {
    [0]=>
    string(1) "4"
    [1]=>
    string(1) "9"
    [2]=> .....
    ..... more elements
  }
  [13703]=>
  array(2) {
    [0]=>
    string(1) "7"
    [1]=>
    string(1) "6"
     .....
    ..... more elements
  }
  [13774]=>
  array(1) {
    [0]=>
    string(1) "7"
    .....
    ..... more elements
  }
}

I want to make it like below

array(
'13702'=> 13,//this is the sum of strings inside it
'13703'=> 13,
'13774'=> 7,
);

Please help

3
  • 1
    Any code attempt? Commented Dec 16, 2020 at 4:13
  • @GetSet I tried this $simplified = array_reduce($pplayerid, 'array_merge', array()); $simplified = array_map('intval', $simplified); but i couldn't manage to assign it to id Commented Dec 16, 2020 at 4:15
  • 1
    Please put code attempt in the actual post, not in a comment. Commented Dec 16, 2020 at 4:16

1 Answer 1

2

No need for array reduce, a simple array_map applying array_sum on each sub array should suffice:

$result = array_map('array_sum', $array);
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome thank you!. I was making it worse

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.