Firs t всего я не говорю, что это конец всем ответам на этот вопрос, но прошло девять месяцев, и я чувствую, что на этот вопрос не ответил, пока он действительно использует его.
Из чего я понимаю, у вас есть два (или более) массива, состоящие из нескольких объектов, которые содержат разные атрибуты одного и того же объекта. Как, например, в следующем примере:
ArrayedObjects1=array(
[0]=>stdClass Object
(
[id] => 1
[name] => foo
)
[1] => stdClass Object
(
[id] => 51
[name] => bar
)
)
ArrayedObjects2=array(
[0]=>stdClass Object
(
[length] => 195
[color] => blue
)
[1] => stdClass Object
(
[length] => 100
[name] => purple
)
)
Прецеденты могут быть очень крупных проектов, где несколько баз данных, которые используются для хранения отдельных значений одного и того же объекта и простые запросы присоединиться не представляется возможным.
Эти два массива могут быть объединены с использованием двух функций, которые я сделал, которые просто позволяют объединить нестандартное количество массивов.
class FooBar {
public function mergeArrayedObjects(){
# We generate a new empty array to return from the function, to which we merge the existing arrays
$returnResponse=array();
# Then we establish the the number of arguments passed to the function
$numArgs=func_num_args();
# As objects are stored within an array of equal length, we loop through the first
for($i=0;$i<count(func_get_arg(0));$i++){
# For each key within the array we merge all existing arrays. We get this number from the number of arguments
# First we check if there already exists an entry into the returnRespone array with the current key. Two choices:
# Case 1 => no: create one by merging the first two arrays into this new array
# Case 2 => yes: merge the existing entry with the next array and recreate it
# BTW we correct $numArgs in the for-loop, as we add 1 to $j in the second case to exclude duplication of work
for($j=0;$j<($numArgs-1);$j++){
# Seems like you can't check on empty with func_get_arg(), so store it in a variable
# We do this as no merge is needed if the array is empty, or the key is empty
$isempty=func_get_arg($j+1);
if(!empty($isempty)||!empty($isempty[$i])){
if(!$returnResponse[$i]){
$array1=func_get_arg($j);
$array2=func_get_arg($j+1);
$returnResponse[$i]=self::mergeObjects($array1[$i],$array2[$i]);
}
else{
$array1=func_get_arg($j+1);
$returnResponse[$i]=self::mergeObjects($returnResponse[$i],$array1[$i]);
}
}
}
}
# Then we return the arrayed objects
return $returnResponse;
}
public function mergeObjects($obj1,$obj2){
# Function to merge objects
$merged_obj= (object) array_merge((array) $obj1, (array) $obj2);
return $merged_obj;
}
}
Это возвращает следующий массив:
$joinArrays=new FooBar;
$joinedArray=$joinArrays->mergeArrayedObjects(ArrayedObjects1,ArrayedObjects2);
$joinedArray=array(
[0]=stdClass Object
(
[id] => 1
[name] => foo
[length] => 195
[color] => blue
)
[1] => stdClass Object
(
[id] => 51
[name] => bar
[length] => 100
[name] => purple
)
)
Как я сказал, что это может быть использовано для неограниченного количества массивов. Если есть более быстрый способ, не стесняйтесь, дайте мне знать. Мне нужно было это для того, чтобы присоединиться к результатам запросов между разными БД, поэтому я просто написал это, так как это делает работу и является достаточно гибким одновременно.
Это также можно расширить, чтобы проверить, является ли одна из записей в объекте массивом и имеет значение array_merge, она добавит две строки кода.