Hello all,

   I have two multidimensional array (associative) and i want to merge them into a new array which contain all the elements that are multidimensional array

  for example

  First array is like [CODE] Array
                             (
                                       [contactId] => 451
                                       [name] => Array
                                                   (
                                                        [fullName] => testing contact

                                                   )

                                       [emails] => Array
                                                 (
                                                        [0] => Array
                                                                (
                                                                      [address] => test@test.com
                                                                )
                                                         [1] =>Array
                                                                (
                                                                       [type]  => work
                                                                )
                                                )
                                       [company] => testing company
                           );

[/CODE]

And here is second array

                          [CODE]   Array
                             (
                                       [contactId] => 451
                                       [name] => Array
                                                   (
                                                        [firstName] => testing contact

                                                   )

                                       [emails] => Array
                                                 (
                                                        [0] => Array
                                                                (
                                                                      [type] => home
                                                                )
                                                         [1] =>Array
                                                                (
                                                                       [address]  => new@test.com
                                                                )
                                                )
                                       [note] => This is simple note
                           );

[/CODE]

So, my final out put is like this;

                           [CODE]  Array
                             (
                                       [contactId] => 451

                                       [name] => Array
                                                   (
                                                        [firstName] => testing contact

                                                        [fullName] => testing contact

                                                   )

                                       [emails] => Array
                                                 (
                                                        [0] => Array
                                                                (
                                                                      [address] => test@test.com
                                                                      [type] => home
                                                                )
                                                         [1] =>Array
                                                                (
                                                                       [address]  => new@test.com
                                                                        [type]  => work
                                                                )
                                                )
                                       [note] => This is simple note
                                       [company] => testing company
                           );[/CODE]

I know there are many ways doing this one but my array have more than 5000 contacts so i want optimize way for merging this type of array

So any quick and faster way for doing this.

Any help will be greatfull

Thanks and regards,
---Amit Patel

    ya like array_merge_recursively

    but i don't have result like array_merge_recursively. i want same result as i mention above means in one array if one field's is not there which is available in second array than it should be merge in same pattern . You observe the result array once more so you can get idea

    Thanks and regards,
    ----Amit patel

      Well, since you have such a "unique" structure, the only thing I could say is for you to use [man]array_map/man or create your own version of [man]array_merge_recursive/man which you loop through each array and do what you need.

      The other option is to use an Object Oriented approach and store all the objects in an array where the key of the array is the contactId. Then you just need to create a small class to hold all the contact information. Then you can do something like:

      /* Create a new object if there isn't already one for this contactId */
      if(!array_key_exists($row['contactId'], $contacts))
          $contacts[$row['contactId']] = new Contact($row['contactId']);
      
      $contacts[$row['contactId']]->setName($row['full_name'], 'full_name')
          ->setName($row['first_name'], 'first_name')
          ->addEmail($row['email'], $row['type'])
          ->setNote($row['note'])
          ->setCompany($row['company']);

      Now your class would be something similar to:

      class Contact 
      {
          private $_contactId;
      
      protected $name;
      protected $address;
      protected $emails;
      protected $phone;
      protected $im;
      protected $note;
      protected $company;
      protected $website;
      
      function __construct($contactId)
      {
          $this->_contactId = intval($contactId);
          $this->emails = array();
          $this->name = array();
          $this->im = array();
      }
      
      public function setName($name, $type='full_name')
      {
          $this->name[$type] = $name;
          return $this;
      }
      
      /* For later use to add an address to this person */
      public function setAddress($address)
      {
      }
      
      /* add an email address, require an email so there are no "empty" addresses */
      public function addEmail($email, $type='home')
      {
          $this->email[] = array('email' => $email, 'type' => $type);
          return $this;
      }
      
      /* For future reference, to add phone numbers, much like emails */
      public function addPhone($phone, $type='home')
      {
      }
      
      /* For future reference to add instant messenger handlers, much like phone numbers */
      public function addIM($handler, $client='aim')
      {
      }
      
      /* Set the note content for this contact */
      public function setNote($note)
      {
          $this->note = $note;
          return $this;
      }
      
      /* Set the company name for this contact */
      public function setCompany($company)
      {
          $this->company = $company;
          return $this;
      }
      
      /* For future reference, set a website for this contact */
      public function setWebsite($url)
      {
          $this->website = $url;
          return $this;
      }
      }

      That's just a general example, and obviously you'd have to filter things like the name, emails, phone numbers, etc. but it gives you an idea as to how to set it up. I would think this would be an easier to maintain approach than having two huge arrays. You could modify the methods to see if there is already content in the variable, and if so maybe add another parameter to be "$overwrite", default it to false. And if there is content, don't modify it if $overwrite is false, otherwise replace the content. Something like:

          public function setNote($note, $overwrite=false)
          {
              if(empty($this->note) || $overwrite == true)
                  $this->note = $note;
      
          return $this;
      }

      Just in case you aren't aware, the "return $this;" in the methods is so that you can chain together method calls, just like in the example I gave above. Otherwise you'd have to do:

      $obj->method();
      $obj->method();
      $obj->method();

      But with this way, you can do:

      $obj->method()->method()->method();

      and achieve the same results.

      Hope that helps.

        Thanks for your interest.

        But i am not knowing more about object oriented approch as you mention. I have attached one file with this thread. In this i have two complete array which i
        want to merge it . Both have a complete elements so can you give me complete example of this if possible.

        I have one function called mergeArray($firstArray, $secondArray) and i want this function returns array which is contatin the merging result.

        So how i can use oops approch on this. If possible that please give me solution.
        Again Thansk for your interest.

        Thank and regards,
        ---Amit patel

          Well, as much as I dislike just giving code away, here's what I came up with.

          <?php
          
          $array1 = array(
          	'contactId' => 1,
          	'name' => array(
          		'firstName' => 'Fully',
          		'middleName' => 'its',
          		'lastName' => 'updated',
          		'prefix' => 'my prefix',
          	),
          	'work' => array(
          		'company' => 'my company',
          		'department' => 'my dept',
          	),
          	'emails' => array(
          		array('address' => 'my@mail.com'),
          		array('type' => 'home'),
          	),
          	'phones' => array(
          		array('number' => '2789015'),
          	),
          	'address' => array(
          		array(
          			'type' => 'home',
          			'formattedAddress' => array(
          				'city' => 'my city',
          				'street' => 'my street',
          			),
          			'isMailing' => 1,
          		),
          	),
          	'communication' => array(
          		'ims' => array(
          			array('address' => 'me@im.com'),
          		),
          		'webUrls' => array(
          			array('url' => 'http://www.mywebsite.com'),
          		),
          	),
          	'extras' => array(
          		'phoneticLastName' => 'my phonetic last name',
          		'dates' => array(
          			'date2' => '2008-09-09',
          		),
          	),
          );
          
          $array2 = array(
          	'contactId' => 4,
          	'lastUpdated' => '2008-09-09 07:06:15',
          	'name' => array(
          		'fullName' => 'Full Name',
          		'suffix' => 'suffix',
          	),
          	'work' => array(
          		'jobTitle' => 'job title',
          	),
          	'emails' => array(
          		array('type' => 'other'),
          		array('address' => 'gmail1@email.com'),
          	),
          	'phones' => array(
          		array('type' => 'work')
          	),
          	'address' => array(
          		array(
          			'type' => 'home',
          			'formattedAddress' => array(
          				'state' => 'guj1',
          				'zip' => '395008',
          				'countryCode' => 'US1',
          			),
          			'isMailing' => 1,
          		),
          	),
          	'communication' => array(
          		'ims' => array(
          			array('protocol' => 'GOOGLE'),
          		),
          		'webUrls' => array(
          			array('type' => 'home'),
          		),
          	),
          	'extras' => array(
          		'phoneticFirstName' => 'fname1',
          		'dates' => array(
          			'date1' => '2008-09-07'
          		),
          	),
          	'note' => '12122notes for this contact123',
          );
          
          /**
           * Recursively merge two arrays together
           *
           * @param array $array1
           * @param array $array2
           * @param boolean $overwrite Defines whether non-array values in $array1 are
           *                           overwritten by those in $array2
           * @return array
           */
          function myArrayMergeRecursive($array1, $array2, $overwrite=true)
          {
          	foreach($array2 as $key=>$val)
          	{
          		if(isset($array1[$key]))
          		{
          			if(is_array($val))
          				$array1[$key] = myArrayMergeRecursive($array1[$key], $val);
          			elseif((is_string($array1[$key]) || is_int($array1[$key])) && $overwrite)
          				$array1[$key] = $val;
          		}
          		else
          			$array1[$key] = $val;
          	}
          
          return $array1;
          }
          
          $array = myArrayMergeRecursive($array1, $array2);
          
          print_r($array);

          This gives me the following output:

          ---------- PHP - Execute ----------
          Array
          (
              [contactId] => 4
              [name] => Array
                  (
                      [firstName] => Fully
                      [middleName] => its
                      [lastName] => updated
                      [prefix] => my prefix
                      [fullName] => Full Name
                      [suffix] => suffix
                  )
          
          [work] => Array
              (
                  [company] => my company
                  [department] => my dept
                  [jobTitle] => job title
              )
          
          [emails] => Array
              (
                  [0] => Array
                      (
                          [address] => my@mail.com
                          [type] => other
                      )
          
                  [1] => Array
                      (
                          [type] => home
                          [address] => gmail1@email.com
                      )
          
              )
          
          [phones] => Array
              (
                  [0] => Array
                      (
                          [number] => 2789015
                          [type] => work
                      )
          
              )
          
          [address] => Array
              (
                  [0] => Array
                      (
                          [type] => home
                          [formattedAddress] => Array
                              (
                                  [city] => my city
                                  [street] => my street
                                  [state] => guj1
                                  [zip] => 395008
                                  [countryCode] => US1
                              )
          
                          [isMailing] => 1
                      )
          
              )
          
          [communication] => Array
              (
                  [ims] => Array
                      (
                          [0] => Array
                              (
                                  [address] => me@im.com
                                  [protocol] => GOOGLE
                              )
          
                      )
          
                  [webUrls] => Array
                      (
                          [0] => Array
                              (
                                  [url] => http://www.mywebsite.com
                                  [type] => home
                              )
          
                      )
          
              )
          
          [extras] => Array
              (
                  [phoneticLastName] => my phonetic last name
                  [dates] => Array
                      (
                          [date2] => 2008-09-09
                          [date1] => 2008-09-07
                      )
          
                  [phoneticFirstName] => fname1
              )
          
          [lastUpdated] => 2008-09-09 07:06:15
          [note] => 12122notes for this contact123
          )
          
          Output completed (0 sec consumed)

          Hope that helps.... I tried to document it pretty well...

            Thanks a lot for your interest.

            I am really thanks to you . As i got result which i wanted. Is it possible to use Object Oriented approach for this type of situation and if yes than how ?

            Because i have more than 5000 contacts so which method is best and give me fast result.

            so how can i write oops class with this situation. if possible

            Thanks and regards,
            ---Amit Patel

              The OO approach would be better served in order to avoid this problem (two arrays needing to be merged) because you'd be forced to use certain methods which you could require parameters.

              This way will work, but for the future, you may want to look at a more OO approach to avoid this type of issue.

                Can you give me the same example with oops approach if you have time so i can some idea how to use oops in this type of issue, if you have time and if possible than only.Again thanx to here my question and give me the reply with details

                Thanks and regards,
                ---amit patel

                  Look up a few posts.... I gave you an example of a class and how to use it...

                    Write a Reply...