[英]Extracting (searching in) a subset of a dictionary?
我想制作一個字典(或列表),該字典是PHP中另一個字典的子集。 請看下面我用Python編寫的代碼:
ThePythons = {
'GC': 'Graham Chapman',
'JC': 'John Cleese',
'EI': 'Eric Idle',
'MP': 'Michael Palin'
}
query = ['EI', 'JC']
output = [[item,ThePythons[item]] for item in query if item in ThePythons]
print(output)
輸出為:
[['EI', 'Eric Idle'], ['JC', 'John Cleese']]
我不知道如何在PHP中完成相同的功能。 請給我相應的PHP代碼。 提前謝謝了!
以下應該工作:
<?php
$thePythons = array(
'GC' => 'Graham Chapman',
'JC' => 'John Cleese',
'EI' => 'Eric Idle',
'MP' => 'Michael Palin'
);
$query = array(0 => 'EI', 1 => 'JC');
$resultList = array();
for ($i=0; $i<sizeof($query); $i++) {
$resultList[$i] = array($query[$i] => $thePythons[$query[$i]]);
}
var_dump($resultList);
?>
產量
array(2) {
[0]=>
array(1) {
["EI"]=>
string(9) "Eric Idle"
}
[1]=>
array(1) {
["JC"]=>
string(11) "John Cleese"
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.