0

I want to use the 'id' array of Array 1 to order all other sibling arrays in Array 2. The 'id' array is supposed to act as the schema for all other arrays in $array1 and $array2.

This is easier explained with an example.

I have the following array, Array 1 :

Array
(
    [id] => Array
        (
            [0] => 1
            [1] => 3
            [2] => 2
        )

    [headline] => Array
        (
            [0] => test 1
            [1] => test 3
            [2] => test 2
        )
)

And another array, Array 2:

Array
(
    [id] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [headline] => Array
        (
            [0] => tc test 1
            [1] => tc test 2
            [2] => tc test 3
        )
)

That I would like to look like the following:

Array
(
    [id] => Array
        (
            [0] => 1
            [1] => 3
            [2] => 2
        )

    [headline] => Array
        (
            [0] => tc test 1
            [1] => tc test 3
            [2] => tc test 2
        )

)

Right now I'm trying to force it with foreach statements (and failing), but there has to be a better way.

1 Answer 1

1

This is a “fake” sort, because I fill an empty array through a foreach() loop, then I replace original array:

$array1 = [ 'id' => [ 1,3,2 ], 'headline' => [ 'test 1','test 3','test 2' ] ];
$array2 = [ 'id' => [ 1,2,3 ], 'headline' => [ 'test 1','test 2','test 3' ] ];

$result = array();
foreach( $array1['id'] as $val )
{
    $key = array_search( $val, $array2['id'] );
    $result['id'][]       = $array2['id'][$key];
    $result['headline'][] = $array2['headline'][$key];
}
$array2 = $result;

print_r( $array2 );

Output:

Array
(
    [id] => Array
        (
            [0] => 1
            [1] => 3
            [2] => 2
        )
    [headline] => Array
        (
            [0] => test 1
            [1] => test 3
            [2] => test 2
        )
)

I execute a foreach loop through criterion 'id' array, find each value in array to be sorted, retrieve its key and use it to add values to resulting array.

Not so proud of this solution, but this is.

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

2 Comments

I'm with ya, I was hoping there would be a more elegant solution. This does work, though. My previous solution had one more foreach, so this is a definite improvement. Made some small edits, but I think this is probably the answer.
@jboneca I see now you suggested edit. I tried it and it doesn't have same result: It double keys and values.

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.