如果两个数组键匹配,则创建一个包含其值的新数组

时间:2016-04-03 12:35:34

标签: php arrays

我有两个阵列。我想基于他们的关键匹配合并。这是我的第一个数组

array(
  (int) 1 => 'Home',
  (int) 7 => 'FAQs',
  (int) 16 => 'Roles',
  (int) 21 => 'Terms & Condition',
  (int) 24 => 'Registration',
  (int) 4 => 'Posts'
)

我的第二个阵列

array(
   (int) 4 => array(
            (int) 0 => 'All Posts',
            (int) 1 => 'Post Add'
   ),
   (int) 7 => array(
            (int) 0 => 'FAQ Add',
            (int) 1 => 'All FAQs'
   ),
   (int) 16 => array(
            (int) 0 => 'Add Role',
            (int) 1 => 'All Role & Actions'
   ),
   (int) 21 => array(
              (int) 0 => 'Add Terms & Condition',
              (int) 1 => 'Terms & Conditions'
    )
 )

我想要做的是创建一个新数组及其值,如果键匹配 这条路。这甚至可以合并它们吗?

 array(
   'Posts' => array(
            (int) 0 => 'All Posts',
            (int) 1 => 'Post Add'
   ),
   'FAQs' => array(
            (int) 0 => 'FAQ Add',
            (int) 1 => 'All FAQs'
   ),
   'Registration' => array(),
   'Home'=>array(),
   'Roles' => array(
            (int) 0 => 'Add Role',
            (int) 1 => 'All Role & Actions'
   ),
   'Terms & Condition' => array(
              (int) 0 => 'Add Terms & Condition',
              (int) 1 => 'Terms & Conditions'
    )
 )

3 个答案:

答案 0 :(得分:2)

<?php
$new_array = array();
foreach($first_array as $key=>$value){
    if(array_key_exists($key, $second_array)){  
     $new_aray[$value] = $arr2[$key];   
    }
}
print_r($new_array);

希望它有所帮助:)

答案 1 :(得分:1)

试试这个循环:

$thirdArray = array();

foreach($firstArray as $fk => $fv){
    if(isset($secondArray[$fk])){
        $thirdArray[$fv] = $secondArray[$fk];
    }
}

var_dump($thirdArray);

答案 2 :(得分:1)

如果您想使用第一个数组作为基础(将所有值保持为键),您可以使用array_maparray_flip尝试此解决方案($menus是您的第一个数组,{{1是第二个数组):

$submenus

$menu = array_map ( function( $key ) use( $submenus ) { return (isset($submenus[$key])) ? $submenus[$key] : array(); }, array_flip( $menus ) ); 数组现在包含:

$menu

eval.in demo

我们使用array_map映射翻转的Array ( [Home] => Array ( ) [FAQs] => Array ( [0] => FAQ Add [1] => All FAQs ) [Menu & Actions] => Array ( ) [Roles] => Array ( [0] => Add Role [1] => All Role & Actions ) [Terms & Condition] => Array ( [0] => Add Terms & Condition [1] => Terms & Conditions ) [Registration] => Array ( ) [Posts] => Array ( [0] => All Posts [1] => Post Add ) ) 数组(array_flip反转键和值):在anonymous function内使用的array_map中,我们搜索在$menus个键中给出$menus值(原始键):如果键存在,我们返回它,否则返回一个空数组。