1

I have two associative arrays

$reference = array(
  'type_drink' => 'value', 
  'type_plate' => 'value', 
  'type_fork' => 'value', 
  'non_type' => 'value'
);
$target = array(
  'type_plate' => 'value other', 
  'type_drink' => 'value other'
);

What's a nice way to re-order target to match $reference order of keys and ignoring keys that are not present in $target so that the final

$target = array(
  'type_drink' => 'value other',
  'type_plate' => 'value other' 
);
1
  • I was gonna say array_intersect_key($target, $reference), but then I noticed you wanted the array sorted. Commented Aug 1, 2013 at 20:36

2 Answers 2

2

Not sure if this is what you need, but here's what I interpret what you're asking for.

foreach($reference as $key => $val)
{
    if(isset($target[$key]))
        $tmp[$key] = $target[$key];
}
$target = $tmp;
Sign up to request clarification or add additional context in comments.

3 Comments

I'd say $tmp[$key] = $target[$key], if I'm reading his question correctly.
That seems to me what he is looking for. Though, he may actually want $tmp[$key] = $target[$key];
@RocketHazmat Now that you mention it, that looks right. THe values per key are different. So I'll edit.
0

http://php.net/manual/en/function.array-intersect-key.php and http://php.net/manual/en/function.ksort.php

ksort(array_intersect_key($target, $reference));

1 Comment

That will sort the keys, but not in the order he wants. Also, you can't the result of array_intersect_key to ksort.

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.