PHP - 重新排序数组以匹配另一个数组的顺序

I have 1 array that has the right values that I need but it is out of order. I then have another array with the same keys and it is in the right order but the values are not what I need.

Here is my first array with the correct values but is out of order:

Array
(
    [countTotal] => 7268
    [zip] => 
    [yearName] => 
    [countZipRadius] => 
    [Acura] => 1334
    [Cadillac] => 511
    [Ford] => 5423
)

Here is my second array with the right order but the wrong values:

Array
(
    [countZipRadius] => 0
    [zip] => 1
    [yearName] => 2
    [Acura] => 3
    [Cadillac] => 4
    [Ford] => 5
    [countTotal] => 6
)

I am trying to figure out a way to create a new array with the right values from array 1 but that is in the order of array 2.

I have been playing with it for awhile and cannot seem to get it.

Any help would be great.

Thanks!

$c = array();
foreach (array_keys($b) as $k) {
    $c[k] = $a[k];
}
  1. Create a New Array (Array C)
  2. Use a FOR loop to go through Array B
  3. For each value in Array B, get the value with the same key from Array A and set Array C append those values to Array C. This will put them in the correct order in C.

Using scones' method:

$original = array(
    'countTotal' => 7268,
    'zip' => '',
    'yearName' => '',
    'countZipRadius' => '',
    'Acura' => 1334,
    'Cadillac' => 511,
    'Ford' => 5423,
    );
$right = array(
    'countZipRadius' => 0,
    'zip' => 1,
    'yearName' => 2,
    'Acura' => 3,
    'Cadilac' => 4,
    'Ford' => 5,
    'countTotal' => 6
);
foreach ($right as $key => $value) {
    $new[$key] = $original[$key];
}
print_r($new);
$array = array('a' => 100, 'b' => '5');

$newArray = array_combine(array_keys($array), range(0, count($array) - 1));

var_dump($newArray);

You could use php's array_multisort function:

$original = array(
    'countTotal' => 7268,
    'zip' => '',
    'yearName' => '',
    'countZipRadius' => '',
    'Acura' => 1334,
    'Cadillac' => 511,
    'Ford' => 5423,
    );

$right = array(
    'countZipRadius' => 0,
    'zip' => 1,
    'yearName' => 2,
    'Acura' => 3,
    'Cadilac' => 4,
    'Ford' => 5,
    'countTotal' => 6
);

//make sure both arrays are in the same order
ksort($original);
ksort($right);

array_multisort($right, $original);

print_r($original);

When you give it two arrays with the same number of elements it sorts both arrays, based on the order of the first array - in this case the 0, 1, 2, 3, etc. values in $right