1

必要なキーのリストを指定して、別の配列から指定されたkey=>value要素の特定のセットで構成される配列を返すためのネイティブPHP関数があるかどうか疑問に思いました。これが私が意味することです:

// 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'
)

私はドキュメンテーションを調べてきましたが、まだ何も見つかりませんが、特にやりたいとは思えないので、質問です。

4

3 に答える 3

3

これはあなたが探しているもののようです: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);
于 2012-09-18T11:34:59.543 に答える
1

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));
于 2012-09-18T11:38:05.423 に答える
0

私は次のコードを試しました:

// 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 )
于 2012-09-18T11:53:37.503 に答える