1

Suppose I have an Object array like this

array 
  0 => 
    object(stdClass)
      public 'ID' => string '1'
      public 'DATE' => string '26/02/2018'
  1 => 
    object(stdClass)
      public 'ID' => string '2'
      public 'DATE' => string '27/02/2018'
  2 => 
    object(stdClass)
      public 'ID' => string '1'
      public 'DATE' => string '28/02/2018'
  3 => 
    object(stdClass)
      public 'ID' => string '3'
      public 'DATE' => string '29/02/2018'

here You can see there are two ids which are same i.e ID=1 but the dates are different. I want to merge the same id and their data like this

array 
  0 => 
    object(stdClass)
      public 'ID' => string '1'
      public 'DATE' => string '26/02/2018, 28/02/2018'
  1 => 
    object(stdClass)
      public 'ID' => string '2'
      public 'DA_DATE' => string '26/02/2018'

  2 => 
    object(stdClass)
      public 'ID' => string '3'
      public 'DATE' => string '27/02/2018'

How to merge the data so I can get two different dates into one for that same id?

2
  • What exactly is the problem, could you show us some code and explain what exactly is not working? Commented Jul 14, 2018 at 9:46
  • If I use array_unique its only depends on a single array. That's why I am asking how to do it because I don't have any idea how to merge the data. Commented Jul 14, 2018 at 9:53

1 Answer 1

3

Assuming you meant the date to be an array:

$grouped = [];

foreach ($items as $item) {
    $grouped[$item->ID]["ID"] = $item->ID;
    $grouped[$item->ID]["DATE"][] = $item->DATE;
}

$grouped = array_values($grouped);

https://3v4l.org/pOio3

And if you want the date to be a string separated by a comma and not an array, then:

$grouped = [];

foreach ($items as $item) {
    $grouped[$item->ID]["ID"] = $item->ID;
    $grouped[$item->ID]["DATE"] = isset($grouped[$item->ID]["DATE"]) ? $grouped[$item->ID]["DATE"] . ", " . $item->DATE : $item->DATE;
}

$grouped = array_values($grouped);

https://3v4l.org/hiSL0

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

3 Comments

Thanks and it's working perfect. But I need to understand $grouped[$item->ID] section. Can you explain me?
@AshisBiswas its a logic in array to identify row by its key
Now I understand after set $grouped[1][1] when go to the same object element the grouped item [1][1] value will be same but if it's has already a date, first check it and concatenate the date with next object element keys value. Thanks for you code

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.