0

I want to combine two arrays of objects. Let me give you an example:

Example:

// First array:

       $array1 = [
         { name => 'Joe', p_id => 1 },
         { name => 'Bob', p_id => 2 },
         { name => 'Sam', p_id => 4 }
        ]
// Second array:

       $array2 = [
         { id => 1, name => 'X'  },
         { id => 2, name => 'Y'  },
         { id => 4, name => 'Z'  }
        ]

Expected output:

 $output = [
  { name => 'Joe + X', id => 1 },
  { name => 'Bob + Y', id => 2 },
  { name => 'Sam + Z', id => 4 }
 ]

Goal:

I want the fastest possible way to combine the name property in the second array with the name property in the first array.

Note: The p_id property in the first array is the same as the id property in the second array.

What i try:

I've used nested loops that have a very low speed.

2 Answers 2

1

array_map is the solution!

Given:

$first = [
    { name => 'Joe', p_id => 1 },
    { name => 'Bob', p_id => 2 },
    { name => 'Sam', p_id => 4 },
];

$second = [
    { id => 1, name => 'X' },
    { id => 2, name => 'Y' },
    { id => 4, name => 'Z' },
];

The solution is just simply:

$result = array_map(
    static function (\stdClass $first, \stdClass $second): array {
        return [
            'name' => $first->name . ' + ' . $second->name,
            'id' => $first->p_id,
        ];
    },
    $first, $second
);

PS: I assume the objects are \stdClass, replace it by the correct one.

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

Comments

0

Here is a solution for when the ids of the elements inside the array are not in order. Notice that I have changed the order of $array1. Just a bit better than the regular nested loops, on the loop of the $array2 it will remove the "found" elements to improve speed of the next loop.

From:

// First array:
$array1 = [
    (object) ['name' => 'Joe', 'p_id' => 1],
    (object) ['name' => 'Sam', 'p_id' => 4],
    (object) ['name' => 'Bob', 'p_id' => 2],
];

// Second array:
$array2 = [
    (object) ['id' => 1, 'name' => 'X'],
    (object) ['id' => 2, 'name' => 'Y'],
    (object) ['id' => 4, 'name' => 'Z'],
];

Solution:

$result = [];
foreach ($array1 as $array1Element) {
  for ($i=0;$i<count($array2);$i++) {
    if ($array1Element->p_id === $array2[$i]->id) {
      $array2[$i]->name = $array1Element->name . ' + ' . $array2[$i]->name;

      $result[] = $array2[$i];
      unset($array2[$i]);
      $array2 = array_values($array2);
      break;
  }
 }
}

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.