PHP的 - 主键排序的数组通过关键字来查找另一个数组的订单 [英] php - sort an array by key to match another array's order by key

查看:320
本文介绍了PHP的 - 主键排序的数组通过关键字来查找另一个数组的订单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个阵列,都具有相同的键(不同的值),但是阵列#2以不同的顺序。我希望能够求助于第二阵列所以它是在相同的顺序第一阵列

I have two arrays, both have the same keys (different values) however array #2 is in a different order. I want to be able to resort the second array so it is in the same order as the first array.

是否有一个功能,可以迅速地做到这一点?

Is there a function that can quickly do this?

推荐答案

我想不出任何把我的头顶部,但如果密钥是相同的在这两个数组又何尝不是在第一个循环刚并使用其键顺序使用从第二一个值,以创建一个新的阵列?

I can't think of any off the top of my head, but if the keys are the same across both arrays then why not just loop over the first one and use its key order to create a new array using the the values from the 2nd one?

$arr1 = array(
    'a' => '42', 
    'b' => '551',
    'c' => '512',
    'd' => 'gge',
) ;


$arr2 = array(
    'd' => 'ordered',
    'b' => 'is',
    'c' => 'now',
    'a' => 'this', 
) ;

$arr2ordered = array() ;

foreach (array_keys($arr1) as $key) {
    $arr2ordered[$key] = $arr2[$key] ;
}

这篇关于PHP的 - 主键排序的数组通过关键字来查找另一个数组的订单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆