开发者

How to merge and asort() two object arrays into one new array?

开发者 https://www.devze.com 2023-02-01 06:20 出处:网络
function sortnme开发者_开发知识库rge($array1,$array2) $all= array_merge_recursive($array1, $array2);
function sortnme开发者_开发知识库rge($array1,$array2)
$all= array_merge_recursive($array1, $array2);
asort($all);

While this works for regular arrays, is there a way to apply it to two array of objects or more?

$all would be the result of merging both contact lists.

Thank you in advance,

JP-


    <?php
   function arrayobj_merge_recursive2($paArray1, $paArray2)
{
    if(is_array($paArray2))
    {
        foreach ($paArray2 AS $sKey2 => $sValue2)
        {
            $paArray1[$sKey2] = arrayobj_merge_recursive2(@$paArray1[$sKey2], $sValue2);
        }
    }
    elseif(is_object($paArray2))
    {   
        foreach ($paArray2 AS $sKey2 => $sValue2)
        {
             $paArray1->{$sKey2} = arrayobj_merge_recursive2(@$paArray1->{$sKey2}, $sValue2);
        } 
    } else {
         return $paArray2;
    }  
   return $paArray1;
}
    ?>


Two steps: define a function to compare the objects, then call usort($all, "cmp"). Example:

<?php

function cmp($a, $b) {
    return $a->some_value > $b->some_value;
}

function sortnmerge($arr1, $arr2) {
    $all = array_merge_recursive($arr1, $arr2);
    usort($all, "cmp");
}
?>

I assume, of course, that you're trying to merge two arrays of objects and then compare them based on some property.

0

精彩评论

暂无评论...
验证码 换一张
取 消