HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Function to combine arrays of associative arrays

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arraysfunctionassociativecombine

Problem

I recently create a function to combine some arrays of associative arrays in a single array in response to a stackoverflow question, where you can found more details about this.

The function works as expected, but I think their description is very obscure. In addition, i choose constant T_OBJECT_CAST as option to convert each rows as object: someone can suggest a better predefined constants?

Goal:

As requested from another user (edited):


I've these two arrays:


1) [0=>['title1'=>'Title 1'], 1=>['title2'=>'Title 2']];


2) [0=>['contn1'=>'Content 1'],1=>['contn2'=>'Content 2']];


How can I combine/merge them that they look like this?


[


0=>['title1'=>'Title 1','contn1'=>'Content 1'],


1=>['title2'=>'Title 2','contn2'=>'Content 2']


]

Explanation:

(Globish here, i'm sorry)

To allow not predetermined arguments, I don't format function as multiArrayCombine( $arg1, $arg2, ... ), I use instead the func_get_args() function, that "allow user-defined functions to accept variable-length argument lists".

First of all, I check if the last argument is the predefined constant T_OBJECT_CAST: if it is, I set $asObject to True, then I pop-it off the end of arguments array; now in the $args variable I have an array with each passed arrays.

Next step: I retrieve the max key value of all passed arrays; i choose this way instead of more comfortable foreach( $array1 as $row ) to avoid to omit values if one of the other arrays have more rows than the first. Eventually not numeric keys are omitted.

Then, the main loop: I process each row of originals arrays and I add their keys and values to row that will added to returned array. If there are duplicated keys, only the last is returned.

After processing each array, i add the obtained row (converted to object if this option is passed) to returning array.

The function:

```
/* Groups passed arrays in an array of associative arrays with same keys and values
*
*

Solution

I know that the question is already answered with cFreed answer but I want show another approach.

While I was finding if there are some function that do that I found this on php.net

function array_merge_recursive_distinct ( array &$array1, array &$array2 )
{
  $merged = $array1;

  foreach ( $array2 as $key => &$value )
  {
    if ( is_array ( $value ) && isset ( $merged [$key] ) && is_array ( $merged [$key] ) )
    {
      $merged [$key] = array_merge_recursive_distinct ( $merged [$key], $value );
    }
    else
    {
      $merged [$key] = $value;
    }
  }

  return $merged;
}


basically is the same that you want but only for two args so...
I tried to do this
pick args and send to that function in pairs

so, I write this. I tried to keep the soul of your code intact so you will see $asObject = (T_OBJECT_CAST == $args[count($args)-1]); and also if($asObject) array_pop($args);

function array_merge_recursive_unique_keys(){
    $args     = func_get_args();
    $asObject = (T_OBJECT_CAST == $args[count($args)-1]);
    if($asObject) array_pop($args);

    $ret = $args;

    if(count($args)>0){
        $partial = current($args);

        for($i = 1; $i< count($args); $i++){
            if(is_array($args[$i]) && is_array($partial)){
                $partial = array_merge_recursive_distinct($partial, $args[$i]);
            }           
        }

        if($asObject) {
            $ret = json_decode (json_encode ($partial), FALSE);
        }else{
            $ret = $partial;
        }

    }

    return $ret;
}

Code Snippets

function array_merge_recursive_distinct ( array &$array1, array &$array2 )
{
  $merged = $array1;

  foreach ( $array2 as $key => &$value )
  {
    if ( is_array ( $value ) && isset ( $merged [$key] ) && is_array ( $merged [$key] ) )
    {
      $merged [$key] = array_merge_recursive_distinct ( $merged [$key], $value );
    }
    else
    {
      $merged [$key] = $value;
    }
  }

  return $merged;
}
function array_merge_recursive_unique_keys(){
    $args     = func_get_args();
    $asObject = (T_OBJECT_CAST == $args[count($args)-1]);
    if($asObject) array_pop($args);

    $ret = $args;

    if(count($args)>0){
        $partial = current($args);

        for($i = 1; $i< count($args); $i++){
            if(is_array($args[$i]) && is_array($partial)){
                $partial = array_merge_recursive_distinct($partial, $args[$i]);
            }           
        }

        if($asObject) {
            $ret = json_decode (json_encode ($partial), FALSE);
        }else{
            $ret = $partial;
        }

    }

    return $ret;
}

Context

StackExchange Code Review Q#118138, answer score: 3

Revisions (0)

No revisions yet.