0

I have a multidimensional array:

$array = array(
    array(
        "name" => "one",
        "date" => "2016-10-10",
        "data"=> 30
    ),
    array(
        "name" => "one",
        "date" => "2016-10-11",
        "data"=> 30
    ),
    array(
        "name" => "two",
        "date" => "2016-10-10",
        "data"=> 40
    )
);

Now I want to merge the difference of arrays, like if an array (name => one) has two dates (2016-10-10 and 2016-10-10) but array (name => two) has only one date (2016-10-10), I want to add 2016-10-11 with array (name => two).

array(
    "name" => "two",
    "date" => "2016-10-11",
    "data"=> 0
)
6
  • I'm sorry I don't understand what you're asking? Commented Dec 1, 2017 at 16:38
  • It difficult to express what really i want :) in short actually i want to add array( "name" => "two", "date" => "2016-10-11", "data"=> 0 ) this. Commented Dec 1, 2017 at 16:39
  • array "name" => "two", don't have the date 2016-10-11 like array "name"=>"one" have, i just want to add this. Commented Dec 1, 2017 at 16:41
  • You want to add the new array with a name of "two" to the original array? Commented Dec 1, 2017 at 16:52
  • Yes, but with the date "201-10-11" that is missing. Commented Dec 1, 2017 at 16:56

1 Answer 1

1

There may be a simpler way I haven't thought of, but I think it looks like the solution takes three steps.

  1. Group your values by date

    foreach ($array as $row) {
        $dates[$row['date']][$row['name']] = $row['data'];
    }
    
  2. Get a unique list of all the names

    $names = array_unique(array_column($array, 'name'));
    
  3. Iterate the date groups and fill the missing values into your original array.

    foreach ($dates as $date => $date_names) {
        foreach ($names as $name) {
            if (!isset($date_names[$name])) {
                $array[] = ['name' => $name, 'date' => $date, 'data' => 0];
            }
        }
    }
    

(This should also work the same if you group by name and get a unique list of dates.)

Sign up to request clarification or add additional context in comments.

1 Comment

That's Perfect. :) Thank you.

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.