0

I have two arrays, say:

Array 1:

Array
(
    [test1] => Array
        (
            [abbrev] => Test data
            [title] => Test data
        )

    [test2] => Array
        (
            [abbrev] => Test data
            [title] => Test data
        )
    [test3] => Array
        (
            [abbrev] => Test data
            [title] => Test data
        )
)

Array 2:

Array
(
    [test1] => Array
        (
            [abbrev] => Test data
            [title] => Test data
        )
    [test3] => Array
        (
            [abbrev] => Test data
            [title] => Test data
        )
)

When array 1 was sorted against array 2, the result would be:

Array
(
    [test1] => Array
        (
            [abbrev] => Test data
            [title] => Test data
        )
    [test3] => Array
        (
            [abbrev] => Test data
            [title] => Test data
        )
    [test2] => Array
        (
            [abbrev] => Test data
            [title] => Test data
        )
)

So test1 and test3 are on top because they were sorted in the same order as in array 2, and test3 was put on bottom because it was not in array 2.

Any ideas?

2 Answers 2

1

This will work fine:

$arrayOne = array('test1'=>array(1, 2, 3),
     'test2'=>array(1, 2, 3),
     'test3'=>array(1, 2, 3),

);

$arraySecond = array('test1'=>array(1, 2, 3),
     'test'=>array(1, 2, 3),

);

foreach ($arraySecond as $key => $arrSecond){
    if (isset($arrayOne[$key])){
      $res[$key]= $arrSecond;
      unset ($arrayOne[$key]);
    }
 }

$res = array_merge($res, $arrayOne);
var_dump($res);

Result is:

 ["test1"]=>
  array(3) {
    [0]=>
    int(1)
    [1]=>
    int(2)
    [2]=>
    int(3)
  }
  ["test3"]=>
  array(3) {
    [0]=>
    int(1)
    [1]=>
    int(2)
    [2]=>
    int(3)
  }
  ["test2"]=>
  array(3) {
    [0]=>
    int(1)
    [1]=>
    int(2)
    [2]=>
    int(3)
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

$array1 = array(...); // array 1
$array2 = array(...); // array 2

$result = array_merge(array_intersect_key($array2, $array1), array_diff_key($array1, $array2));

Demo

1 Comment

This also worked, but @sergio was a few minutes ahead of you.

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.