【问题标题】:Returning an array of given keys from an array从数组中返回给定键的数组
【发布时间】:2012-09-18 11:28:57
【问题描述】:

我想知道是否有一个原生 PHP 函数用于返回一个数组,该数组由另一个数组中的一组给定 key=>value 元素组成,给定一个需要键的列表。这就是我的意思:

// Nice information
$source_array = array('a' => 'hello', 'b' => 'goodbye', 'c' => 'good day', 'd' => 'sunshine');

// Required element keys
$array_two = array('a','b');
$array_three = array('a','d');

// Get that stuff from $source_array...
// $array_two_result = ???
// $array_three_result = ???

// Show it
print_r($array_two_result);
print_r($array_three_result);

输出:

Array(
    [a] => 'hello'
    [b] => 'goodbye'
)
Array(
    [a] => 'hello'
    [d] => 'sunshine'
)

我一直在查看文档,但目前还没有找到任何东西,但在我看来,这并不是一件特别不正常的事情,因此提出了这个问题。

【问题讨论】:

    标签: php


    【解决方案1】:

    这似乎就是你要找的东西:array_intesect_key

    $source_array = array('a' => 'hello', 'b' => 'goodbye', 'c' => 'good day', 'd' => 'sunshine');
    
    // Required element keys
    $array_two = array('a','b');
    $array_three = array('a','d');
    
    // Get that stuff from $source_array...
    $array_two_result = array_intersect_key($source_array, array_flip($array_two));
    $array_three_result = array_intersect_key($source_array, array_flip($array_three));
    
    // Show it
    print_r($array_two_result);
    print_r($array_three_result);
    

    【讨论】:

      【解决方案2】:

      array_intersect_key - IT 使用键计算数组的交集以进行比较。您可以将它与 array_flip 一起使用

      print_r(array_intersect_key($source_array, array_flip(array_two_result));
      print_r(array_intersect_key($source_array, array_flip($array_three_result));
      

      【讨论】:

        【解决方案3】:

        我试过以下代码:

        // Nice information
        $source_array = array('a' => 'hello', 'b' => 'goodbye', 'c' => 'good day', 'd' => 'sunshine');
        
        // Required element keys
        $array_two = array('a','b');
        $array_three = array('a','d');
        
        function getArrayValByKey($keys_arr, $source_array){
        $arr = array();
        foreach($keys_arr as $key => $val){
            if(array_key_exists($val, $source_array)){
                $arr[$val] = $source_array[$val];;
            }
        }
        
        return $arr;
        }
        
        // Get that stuff from $source_array...
        $array_two_result = getArrayValByKey($array_two, $source_array);
        $array_three_result = getArrayValByKey($array_three, $source_array);
        
        // Show it
        print_r($array_two_result); //Array ( [a] => hello [b] => goodbye ) 
        print_r($array_three_result); //Array ( [a] => hello [d] => sunshine )
        

        【讨论】:

          猜你喜欢
          • 2022-01-22
          • 2012-09-14
          • 1970-01-01
          • 1970-01-01
          • 2020-09-09
          • 2011-02-28
          • 2019-07-24
          • 2019-07-10
          • 1970-01-01
          相关资源
          最近更新 更多