0

I have 2 Arrays:

(1) Array with Key => Value, and Array (2) with no relevant Keys and as Values the keys from array 1 in different order. Is there an elegant solution to put array 1 in the same order like the values in array two?

$data = array(
'NAME' => 'XYZ',
'NUMB' => 1234,
'CITY' => 'TEST'
);

$sort = array(
'A1' => 'CITY',
'XY' =>  'NUMB',
'XX' => 'NAME',
);

$result = array(
'CITY' => 'TEST,
'NUMB' => 1234,
'NAME' => 'XYZ',
);
3
  • Not really seeing the logic here, particularly for 'NUMB' => 1234. Commented Jul 20, 2012 at 8:20
  • in array 2, 1234 if not a key in array 1. Commented Jul 20, 2012 at 8:20
  • is that a mistake in writing question ? I mean 1234 ? Commented Jul 20, 2012 at 8:21

2 Answers 2

2
$data = array(
    'NAME' => 'XYZ',
    'NUMB' => 1234,
    'CITY' => 'TEST'
);

$sort = array(
    'A1' => 'CITY',
    'XY' => 'NUMB',
    'XX' => 'NAME'
);

$result = array();
foreach($sort as $key => $value){
    if(isset($data[$value]))
        $result[$value] = $data[$value];
}

print_r($result);
Sign up to request clarification or add additional context in comments.

1 Comment

as you didn't mention anything about 1234, I am expecting that a mistake in writing question.
2

I noticed the typo, and think you want this:

$result=array();
foreach ($sort as $var=>$val){
    $result[$val]=$data[$val];
}

Comments

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.