0

i have a problem with this array, i need get sum form string merge with same key

$data = array(
        0 => array(
          'name' => 'Alfa Edison, Dwiki',
          'budget' => 3700,
        ),
        1 => array(
          'name' => 'Maverick Sam',
          'budget' => 500,
        ),
        2 => array(
          'name' => 'Dwiki',
          'budget' => 1000,
        ),
        3 => array(
          'name' => 'Steve, Dwiki',
          'budget' => 2000,
        ),
        4 => array(
          'name' => 'Alfa Edison',
          'budget' => 700,
        ),
        5 => array(
          'name' => 'Maverick Sam',
          'budget' => 4000,
        ),
        6 => array(
          'name' => 'Steve, Alfa Edison',
          'budget' => 334,
        ),
      );

i want the result this:

array(
        0 => array(
          'name' => 'Alfa Edison',
          'budget' => 4734,
        ),
        1 => array(
          'name' => 'Dwiki',
          'budget' => 6700,
        ),
        2 => array(
          'name' => 'Maverick Sam',
          'budget' => 4500,
        ),
        3 => array(
          'name' => 'Steve',
          'budget' => 2334,
        ),
      );

How to merge String with same Key and Sum the Budget. i try to for each but i'm fail. i try array_reduce and explode the name but fail.

1
  • 1
    Please show what you have tried so far - even if it didn't work, it may be easy to show where you failed. Commented Feb 3, 2020 at 17:12

1 Answer 1

1

The problem is that each of the "keys" (names) is really more than one key. So as you iterate the input array you'll need to split those up, then add an inner loop to use the names as keys in the result.

foreach ($data as $item) {

    // separate the names
    $names = explode(', ', $item['name']);

    // iterate the names and set/increase values for them in the result array
    foreach ($names as $name) {
        $result[$name]['name'] = $name;
        $result[$name]['budget'] = $item['budget'] + ($result[$name]['budget'] ?? 0);
    }
}

// remove the string keys if necessary
$result = array_values($result);
Sign up to request clarification or add additional context in comments.

Comments

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.